在Web开发者专业JavaScript书中,有一种技术叫做寄生组合式继承。我不明白为什么需要获取原型的克隆,为什么不直接将子类型的原型设置为父类型(超类型)的原型。
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
}