在面向 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
}