【问题标题】:JS "inheritance" (code sharing) mechanismJS“继承”(代码共享)机制
【发布时间】:2014-04-01 11:04:33
【问题描述】:

我最近已经走出了我对 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://'; 
}

此代码按我预期的方式工作(使 URL 上的“方法”在 HttpURL 上可用,但反之亦然),但我想知道它是否“合乎道德”,或者是否有更好的方法允许这样做。

【问题讨论】:

  • 还有什么问题?两个对象共享相同的代码是否合乎道德? )
  • 这正是人们在 Javascript 中轻松管理继承方案的方式。赞!如果您在不支持Object.create 的旧环境中工作,您将需要做更多的工作,但这是正确的想法。

标签: javascript inheritance prototype


【解决方案1】:

共享通用功能有意义的情况。

subclass(URL, HttpURL)

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

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

此代码按我的预期工作(在 URL 上创建“方法” 在 HttpURL 上可用,但反之则不行)

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

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

否则不会被继承。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-21
    • 2013-03-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多