以下代码演示了经典的寄生组合式的继承方式:
<html>
<head>
</head>
<body>
<script>
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();
</script>
</body>
</html>