1. 程式人生 > >JavaScript通用繼承方法和super

JavaScript通用繼承方法和super

1、JavaScript通用繼承的封裝和super的使用

/**
		 * JavaScript通用繼承的封裝
		 * @param {Object} Child 子物件
		 * @param {Object} Parent 子物件要繼承的父物件
		 */
		function createExtend(Child, Parent) {
			function F() {}
			F.prototype = Parent.prototype;
			Child.prototype = new F();
			Child.prototype.constructor = Child;
			//新增父類的指標
			Child.super = Child.base = Parent.prototype;
		}

2、測試程式碼

<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<script>
		/**
		 * JavaScript通用繼承的封裝
		 * @param {Object} Child 子物件
		 * @param {Object} Parent 子物件要繼承的父物件
		 */
		function createExtend(Child, Parent) {
			function F() {}
			F.prototype = Parent.prototype;
			Child.prototype = new F();
			Child.prototype.constructor = Child;
			//新增父類的指標
			Child.super = Child.base = Parent.prototype;
		}

		//父類的定義
		function Person(name, age) {
			this.name = name;
			this.age = age;
		}
		Person.prototype.headCount = 1;
		Person.prototype.eat = function() {
			console.log("eating ...");
		}

		//子類的定義
		function Programer(name, age, title) {
			Person.apply(this, arguments);
			this.title = title;
		}
		//繼承的實現
		createExtend(Programer, Person);
		//在繼承之後,再往子類的原型加方法和屬性
		Programer.prototype.language = "JavaScript";
		Programer.prototype.work = function() {
			console.log("I am writing code in " + this.language);
			//繼承的方法
			this.eat();
		}
		//測試程式碼
		var pro = new Programer("zhang", 18, "haah");
		pro.work();
	</script>

	<body>
	</body>

</html>