js类式继承
js继承主要分为类式继承和原型式继承。
?
类式继承:大概思路1 继承其构造函数,2.继承其方法,3 声明其构造结果 4 覆盖和扩充自己的方法
首先定义一个常用类Person
//定义构造函数function Person(name){this.name=name}//定义类的公用方法Person.prototype.getName=function(){return this.name}//创建Person对象调用var boy=new Person("mali");boy.getName();?创建一个新类Author来进行继承Person
function Author(name,books){//继承其构造函数 Person.call(this,name); this.books=books;}//继承其公用方法Author.prototype=new Person();//声明其构造器Author.prototype.constructor=Author;//对类进行方法扩展Author.prototype.getBooks=function(){return this.books;}?为了简化类的声明,可以对整个过程进行包装,声明一个extend函数。
下面的封装函数对继承父类的方法进行了封装,但并没有对其构造函数进行继承,需要手动调用call来完成
?
function extend(subclass,superclass){//定义一个新对象 作用是避开调用superclass的构造函数 var F=function(){};//将superclass的公用方法继承到F对象中 F.prototype=superclass.prototype;//再使用subclass来继承F subclass.prototype=new F();subclass.prototype.constructor=subclass;}这样继承的话function Author(name,book){Person.call(this,name);this.book=book;}extends(Author,Person);Author.prototype.getBook=function(){return this.book;}