【发布时间】:2013-11-27 00:21:53
【问题描述】:
我使用这种 (prototype) 方法定义了两个 javascript 类:
function Parent () {
this.a = 1;
}
Parent.prototype = {
hello : function () {
return "Hello I'm Parent!";
},
setA : function (a) {
this.a = a;
}
};
和
function Child () {
this.b = 2;
}
Child.prototype = new Parent();
Child.prototype.constructor = Child;
Child.prototype = {
hello : function () {
return "Hello I'm Child!";
},
setB : function (b) {
this.b = b;
}
};
我使用这种技术是因为我认为标准语法过于冗长和稀疏:
Child.prototype.hello = function () {...};
Child.prototype.setB = function (b) {...};
这里的问题是我覆盖 Child.prototype(继承自Parent)失去了.setA() 方法(但正确地覆盖 .hello())。
合并两个原型是解决方案吗?怎么样?
这种方法会导致问题吗?
【问题讨论】:
-
考虑继承:
Child.prototype = Object.create(new Parent()); -
@Matías 您可以使用 Object.create 或辅助函数来防止在设置继承的原型部分时创建 Parent 实例,因此它应该是:
Child.prototype = Object.create(Parent.prototype);您和 OP 的方式Parentthis.someting的每个实例特定成员都放在 Child 原型上,并且(如果你做得正确的话)在创建 Child 实例时立即隐藏(Parent.apply(this, arguments) in Child body)。或者更糟;程序员假定 Child 具有 Parent 的实例成员,但没有意识到它们实际上是共享的。
标签: javascript oop inheritance