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

JavaScript中的寄生组合式继承方式

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

以下代码演示了经典的寄生组合式的继承方式:

<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>

抱歉!评论已关闭.