javascript實現基於類的繼承

我們知道javaScript沒有“類”的概念,那javascript是不是就不能實現繼承了呢?答案是否定的,下面的例子就實現了兩個類的繼承。
Person 是父類,Student是子類,extend是實現兩個對象的繼承的函數,“subClass.superClass = superClass.prototype.constructor”是在子類添加一個靜態的屬性保存父類的constructor,方便對父類屬性的拷貝繼承, “Student.superClass.call(this,name,age); // 屬性繼承”便是實現了對父類屬性的拷貝繼承。實現兩個類的集成只需調用extend函數即可完成繼承。


<head>
		<title>index.html</title>
		<style>
		</style>
		<script type="text/javascript" >
		
			// Super class
			var Person = function(name,age) {
				this.name = name;
				this.age = age;
				this.books = [];
			};
			
			Person.prototype.getBooks = function() {
				return this.books;
			};
			
			// sub Class
			var Student = function(no,name,age) {
				this.no = no;
				Student.superClass.call(this,name,age); // 屬性繼承
			};
			
			// 繼承
			function extend(subClass,superClass) {
				var F = function() {};
				F.prototype = superClass.prototype;
				subClass.prototype = new F();
				subClass.superClass = superClass.prototype.constructor;
				
			};
			
			//Student.prototype = new Person();
			extend(Student,Person);
			
			Student.prototype.show = function() {
				alert(this.name + "," + this.age);
			};
			
			var stu1 = new Student("wangmei",26);
			stu1.books.push("java");
			alert(stu1.getBooks());
			
			var stu2 = new Student("jiashu",28);
			stu2.books.push("javascript");
			alert(stu2.getBooks());	
			
					
		</script>
	</head>
	<body >
	<input type="button" value="getData" id="getData" οnclick="getData()"/>
	<div id="data">
		
	</div>
	</body>
</html>


發佈了24 篇原創文章 · 獲贊 16 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章