小编DPG*_*DPG的帖子

Javascript原型继承:当父和子接收相同的对象作为参数时出现问题?

我试图通过以下方式获得原型继承:

// 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给父母和孩子似乎都会引起问题; 当孩子试图通过原型时,Parentobj是不确定的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)

当然有更好的方法,但我无法在任何地方找到答案.请帮忙!!

javascript inheritance constructor prototype

3
推荐指数
1
解决办法
2423
查看次数

标签 统计

constructor ×1

inheritance ×1

javascript ×1

prototype ×1