我使用这种(原型(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()
)。
合并两个原型(prototype)是解决方案吗?怎么办?
这种方法会导致问题吗?
最佳答案
Is merging the two prototypes the solution?
是的。
How?
只需编写一个循环来运行对象文字并将每个属性合并到原型(prototype)中。
function inherit(Child, Parent, methods) {
var p = Child.prototype = Object.create(Parent.prototype);
p.constructor = Child;
for (var m in methods)
p[m] = methods[m];
return p;
}
function Child () {
Parent.call(this);
this.b = 2;
}
inherit(Child, Parent, {
hello : function () {
return "Hello I'm Child!";
},
setB : function (b) {
this.b = b;
}
});
关于Javascript继承与简洁的原型(prototype)赋值语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20230696/