javascript实现基于类的继承

来源:互联网 发布:淘宝在线店招制作 编辑:程序博客网 时间:2024/06/06 02:54

我们知道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 classvar Person = function(name,age) {this.name = name;this.age = age;this.books = [];};Person.prototype.getBooks = function() {return this.books;};// sub Classvar 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" onclick="getData()"/><div id="data"></div></body></html>


1 0
原创粉丝点击