【发布时间】: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