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>


发布了29 篇原创文章 · 获赞 15 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/han_han_1/article/details/45510631