DPG*_*DPG 3 javascript inheritance constructor prototype
我试图通过以下方式获得原型继承:
// Parent constructor
function Parent(obj) {
this.id = obj.id || 0;
this.name = obj.name || "";
};
// Child constructor
function Child(obj) {
Parent.call(this,obj);
this.type = obj.type || "";
}
Child.prototype = new Parent;
Run Code Online (Sandbox Code Playgroud)
似乎教科书......但传递obj给父母和孩子似乎都会引起问题; 当孩子试图通过原型时,Parent说obj是不确定的Child.prototype = new Parent;.我可以解决这个问题的唯一方法是使用这个丑陋的黑客:
// 'Hacked' Parent constructor
function Parent(obj) {
if (obj) {
this.id = obj.id || 0;
this.name = obj.name || "";
}
};
Run Code Online (Sandbox Code Playgroud)
当然有更好的方法,但我无法在任何地方找到答案.请帮忙!!
Child.prototype = new Parent;创建一个没有任何参数的新Parent,并返回其原型,并将其分配给Child.prototype.这种方法运行良好,但问题是它只适用于具有0个参数的父项(在此上下文中new Parent等效new Parent()).
对于带参数的父构造函数,我建议定义一个继承函数来处理你的继承.
我之前提出的修正案是Child.prototype = Parent.prototype;.这将工作,但现在Child.prototype是一个参考来Parent.prototype,而不是一个对象.换句话说,如果将方法hello添加到Child,则Parent也会接收该方法.艰难时期!
解决此问题的最佳方法是定义一些inherits函数:
function inherit(parentPrototype) {
function F() {};
F.prototype = parentPrototype;
return new F;
}
Run Code Online (Sandbox Code Playgroud)
我们在这里所做的与仅仅分配Parent.prototype给孩子略有不同.我们正在创建一个具有父级原型的新函数,并返回函数F的新实例.因此,当您向Child添加方法时,实际上是将它们添加到F函数的原型中.
要立即创建Child对象,您需要:
function Child() {};
Child.prototype = inherit(Parent.prototype); // returns an instance of F
Run Code Online (Sandbox Code Playgroud)
然后,您可以在不影响Parent的情况下向Child添加方法.
| 归档时间: |
|
| 查看次数: |
2423 次 |
| 最近记录: |