JavaScriptにおける寄生結合式の継承方式
801 ワード
以下のコードは古典的な寄生結合式の継承方式を示している.
function object(o){
function F(){};
F.prototype = o;
return new F();
}
function inheritPrototype(subType, superType){
var proto = object(superType.prototype);
proto.constructor = subType;
subType.prototype = proto;
}
function SuperType(name){
this.name = name;
}
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);
};
var instance1 = new SubType("Nicholas", 29);
instance1.sayName();
instance1.sayAge();
var instance2 = new SubType("Greg", 27);
instance2.sayName();
instance2.sayAge();