【发布时间】:2014-11-10 16:32:21
【问题描述】:
我一直在为 JavaScript 对象/类继承而苦苦挣扎。我也不喜欢我能找到的所有示例中的重复代码(对象名称需要写几次)。
据我了解,JavaScript 中的正确继承如下所示:
function Parent(v) {
console.log('Parent', v);
}
Parent.prototype.helloParent = function() {
console.log('hello parent');
}
function Child(v) {
Parent.call( this, 'from child');
console.log('Child');
}
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
Child.prototype.helloChild = function() {
console.log('hello child');
}
c = new Child();
console.log(c instanceof Child);
c.helloParent();
c.helloChild();
在这个例子中,为了扩展“Parent”对象,我必须写“Child”四次,“Parent”两次。我想只输入一次——因为DRY。
我也不想为这个继承的东西定义一个自定义函数。我觉得很奇怪,需要一个用户函数来实现这样一个基本功能(而且阅读未知代码变得越来越困难,因为你永远不知道这个特定的继承函数到底在做什么)。
所以我试图找到一个更简单的版本。但是我不确定我是否错过了什么?
function Parent(v) {
console.log('Parent', v);
this.helloParent = function() {
console.log('hello parent');
}
}
(Child = function(v) {
this.constructor('from child');
console.log('Child');
this.helloChild = function() {
console.log('hello child');
}
}).prototype = Parent.prototype;
c = new Child();
console.log(c instanceof Child);
c.helloParent();
c.helloChild();
这样可以吗?还是有严重的缺点?
编辑:关于 cmets,遗憾的是它似乎有一些严重的缺点。有没有其他的方案可以减少至少多次写入父对象的名字?
【问题讨论】:
-
为什么不把这些方法放在原型上呢? (如果您尝试,您可能会注意到第一个缺点)。
-
您没有进行继承,而是将
Child.prototype替换为Parent.prototype,因此它们是同一个对象。这感觉更像是一次代码审查。考虑codereview.stackexchange.com -
查看我最近回答的这个问题。它应该可以帮助您了解缺点和其他替代方法:stackoverflow.com/questions/26595866/…
-
原型和继承在这里解释:stackoverflow.com/questions/16063394/…
标签: javascript class oop inheritance prototype