今天看《JavaScript高级程序设计》一书中关于组合继承模式时,书上有这么一个Demo程序:
<html>
<head>
</head>
<body>
<script>
function SuperType(name){
this.name = name;
}
SuperType.prototype.sayName = function(){
alert(this.name);
};
function SubType(name, age){
SuperType.call(this, name);
this.age = age;
}
SubType.prototype = new SuperType();//SuperType.prototype;
SubType.prototype.sayAge = function(){
alert(this.age);
};
var instance1 = new SubType("Nicholas", 29);
instance1.sayName();
instance1.sayAge();
//var instance2 = new SuperType("Greg", 27);
//instance2.sayAge();
</script>
</body>
</html>仔细考虑之后,我把Demo做了如下的修改,弄清楚了这么做的理由何在:
<html>
<head>
</head>
<body>
<script>
function SuperType(name){
this.name = name;
}
SuperType.prototype.sayName = function(){
alert(this.name);
};
function SubType(name, age){
SuperType.call(this, name);
this.age = age;
}
SubType.prototype = SuperType.prototype;
SubType.prototype.sayAge = function(){
alert(this.age);
};
var instance1 = new SubType("Nicholas", 29);
instance1.sayName();
instance1.sayAge();
var instance2 = new SuperType("Greg", 27);
instance2.sayAge();
</script>
</body>
</html>JavaScript组合继承的一点思考,布布扣,bubuko.com
原文地址:http://blog.csdn.net/softmanfly/article/details/35280541