我试图通过以下方式获得原型继承:
// 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)
当然有更好的方法,但我无法在任何地方找到答案.请帮忙!!