标签:今天 父类 release name href styles https lin def
今天看《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>
为何非要new一个出来?
细致考虑之后。我把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>
假设你把这句换成SubType.prototype = new SuperType()的话再去调用sayAge方法就会执行出错。由于父类型这时候并没有这种方法(没有被子类型污染)。所以说使用new是很科学合理的。
标签:今天 父类 release name href styles https lin def
原文地址:https://www.cnblogs.com/mqxnongmin/p/10541100.html