这两种继承策略有什么区别?

时间:2012-08-04 01:17:47

标签: javascript inheritance prototype

我认为它们是等价的,但我不确定:

var __extends = function(child, parent) { 
    for (var key in parent) { 
        if (__hasProp.call(parent, key)) child[key] = parent[key]; 
    }
    function ctor() { 
        this.constructor = child; 
    } 
    ctor.prototype = parent.prototype; 
    child.prototype = new ctor; 
    child.__super__ = parent.prototype;
    return child; 
};

var __extends = function(child, parent) { 
    for (var key in parent) { 
        if (__hasProp.call(parent, key)) child[key] = parent[key]; 
    }
    child.prototype = parent.prototype;
    child.prototype.constructor = child;
    child.__super__ = parent.prototype;
    return child; 
};

1 个答案:

答案 0 :(得分:1)

两个函数都使用child对象的所有属性扩展parent(函数)对象,并设置__super__属性。然后差异开始了:

function ctor() { 
    this.constructor = child; 
} 
ctor.prototype = parent.prototype; 
child.prototype = new ctor;

此代码为child创建一个继承自parent.prototype的原型对象。它是old version所做的Object.create()。这是经典的JavaScript继承模式。

child.prototype = parent.prototype;
child.prototype.constructor = child;
child.__super__ = parent.prototype;

此代码是废话。它将child的原型对象设置为parent.prototype,但在下一行中忘记了,现在两个属性都指向同一个对象(child.prototype === parent.prototype)。因此,parent.prototype.constructor === childchild.__super__ === child.protoype - urgh。