JS“继承”(代码共享)机制

时间:2014-04-01 11:04:33

标签: javascript inheritance prototype

我最近一直在使用JS走出我的舒适区,并遇到了分享常见功能的情况。我想出的是以下(仅概念)代码:

function subclass(parent, child) {
  child.prototype = Object.create(parent.prototype)
}

function URL(str) {
    this.value = str;
}

function HttpURL(str) {
    this.value = str
}

subclass(URL, HttpURL)

URL.path = function() { 
    return this.value; 
}
// ...

HttpURL.isSecure = function() { 
    this.value.substring(0, 8) === 'https://'; 
}

这段代码可以正常工作(在HttpURL上使URL上的“方法”可用,但反之亦然),但我想知道它是“道德的”还是有更好的方法允许它。

1 个答案:

答案 0 :(得分:0)

  

分享共同功能是有意义的。

subclass(URL, HttpURL)

是的,这有效并且是correct解决方案。

URL.path = function() { 
    return this.value; 
}
HttpURL.isSecure = function() { 
    this.value.substring(0, 8) === 'https://'; 
}
     

此代码可以正常工作(在URL上创建“方法”)   在HttpURL上可用,但反之亦然)

没有。您希望在HttpUrl 实例上提供URL方法,您需要使用原型:

URL.prototype.path = function() { 
    return this.value; 
}
HttpURL.prototype.isSecure = function() { 
    this.value.substring(0, 8) === 'https://'; 
}

否则他们不会被继承。