3

面向 Web 开发人员的专业 JavaScript 中,有一种称为寄生组合继承的技术。我不明白为什么你需要得到原始原型的克隆,为什么不直接将SubType原型设置为父原型(SuperType)。

function object(o){
    function F(){}
    F.prototype = o;
    return new F();
}

function inheritPrototype(subType, superType){
    var prototype = object(superType.prototype); //create object -- why this is needed?
    prototype.constructor = subType; //augment object
    subType.prototype = prototype; //assign object
}

function SuperType(name){
    this.name = name;
    this.colors = ["red", "blue", "green"];
}
SuperType.prototype.sayName = function(){
    alert(this.name);
};

function SubType(name, age){
    SuperType.call(this, name);
    this.age = age;
}

inheritPrototype(SubType, SuperType);
SubType.prototype.sayAge = function(){
    alert(this.age);
};

我尝试像这样更改它并且它有效:

function inheritPrototype(subType, superType){
    var prototype = superType.prototype;
    prototype.constructor = subType; //augment object
    subType.prototype = prototype; //assign object
}
4

1 回答 1

3

在您的方法中,您只是对父原型的引用进行别名。因此,每当您将方法添加到“子原型”时,它实际上只是将其添加到父原型中。

而且第一种方法不复制父原型,以后添加到父原型的任何方法都会被继承,它不是快照/副本。

于 2013-08-16T18:08:43.877 回答