简洁的原型分配语法实现Javascript继承 [英] Javascript inheritance with concise prototype assignment syntax
问题描述
我已经使用这种(prototype
)方法定义了两个javascript类:
I've defined two javascript classes using this (prototype
) approach:
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;
}
};
我之所以使用这种技术,是因为我认为它的标准语法过于冗长和稀疏:
I'm using this technique because I think that the standard syntax it's too verbose and sparse:
Child.prototype.hello = function () {...};
Child.prototype.setB = function (b) {...};
这里的问题是我覆盖 Child.prototype
(继承自Parent
)丢失了.setA()
方法(但正确地覆盖了覆盖 .hello()
).
The problem here is that I'm overwriting Child.prototype
(inherited from Parent
) losing .setA()
method (but correctly overriding .hello()
).
合并两个原型是解决方案吗?怎么样?
这种方法会导致问题吗?
Is merging the two prototypes the solution? How?
Can this approach lead to problems?
推荐答案
将两个原型合并为解决方案吗?
Is merging the two prototypes the solution?
是的
如何?
只需编写一个循环遍历对象文字并将每个属性合并到原型中即可.
Simply write a loop that runs over the object literal and merges each property into the 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继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!