现在的位置: 首页 > 综合 > 正文

JavaScript组合继承的一点思考

2017年12月19日 ⁄ 综合 ⁄ 共 1430字 ⁄ 字号 评论关闭

今天看《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>

其中的SubType.prototype = new SuperType()让我产生了疑问,这个语句的目的不就是要让子类型的原型指向父类型的原型实例吗?为什么不直接写出SubType.prototype = SuperType.prototype呢?为何非要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>

运行以后会发现instance2.sayAge弹出的提示是undefined,也就是说我们在为子类型的添加一个子类型想要持有的方法sayAge时,不小心也污染了父类型,使得父类型也同样拥有了sayAge方法,而父类型根本不具有age属性,当然就会提示这个属性undefined了,这些奇怪现象出现的原因就是直接使用了SubType.prototype = SuperType.prototype造成的。如果你把这句换成SubType.prototype = new SuperType()的话再去调用sayAge方法就会执行出错,因为父类型这时候并没有这个方法(没有被子类型污染),所以说使用new是非常科学合理的。

抱歉!评论已关闭.