【发布时间】:2011-07-31 14:57:54
【问题描述】:
我试图让原型继承以下列方式工作:
// 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;
似乎教科书......但将obj 传递给父母和孩子似乎会导致问题; Parent 表示当孩子试图通过 Child.prototype = new Parent; 进行原型制作时,obj 未定义。我可以解决这个问题的唯一方法是使用这个丑陋的黑客:
// 'Hacked' Parent constructor
function Parent(obj) {
if (obj) {
this.id = obj.id || 0;
this.name = obj.name || "";
}
};
当然有更好的方法,但我在任何地方都找不到答案。请帮忙!!
【问题讨论】:
标签: javascript inheritance prototype constructor