在Professional JavaScript for Web Developers书中有一种技术叫做Parasitic Combination Inheritance。我不明白为什么你需要获得原始原型(prototype)的克隆,为什么不直接将 SubType 原型(prototype)设置为父级(SuperType)的原型(prototype)。
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
}
最佳答案
在您的方法中,您只是为对父原型(prototype)的引用设置了别名。因此,无论何时向“子原型(prototype)”添加方法,它实际上只是将其添加到父原型(prototype)。
并且第一种方式不复制父原型(prototype),任何后来添加到父原型(prototype)的方法都是继承的,它不是快照/复制。
关于javascript - 为什么Parasitic Combination Inheritance中需要复制原型(prototype)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18279531/