我定义使用这个(prototype
)方法有两个JavaScript类: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(新父());' –
@马蒂亚斯可以使用的Object.create或一个辅助函数,用于在设置继承的原型部分时防止创建一个Parent实例,所以它应该是:'Child.prototype = Object.create(Parent.prototype);'您和OP执行它的每个实例特定成员的方式在Child实例中创建一个Child实例(Parent.apply(this,arguments))时,父'this.someting'被放置在Child原型上,并且(如果您正确地做到这一点)立即被遮蔽。或更糟;程序员假定Child有Parent的实例成员,并没有意识到他们实际上是共享的。 – HMR