浅析2种JavaScript继承方式
js继承方法最主要的是2种,一种是通过原型的方式,一种是通过借用call&apply的构造函数方式。
1.原型(prototype):
functionBody(name,age){//创建一个Body类 this.name=name;//赋予基础属性name、age this.age=age; } Body.prototype.sayName=function(){//给原型定义一个sayName的方法 console.log(this.name); } vara=newBody('wutao','10');//创建一个Body的实例对象 functionAnother(){} Another.prototype=newBody('www');//将Body实例对象给新创建的子类(Another)的prototype属性,这样,Another就拥有了Body的属性和方法 varb=newAnother();//创建Another子类的实例 Another.prototype.sex="mail";//定义子类的属性及方法 Another.prototype.saySex=function(){ console.log(this.sex); } a.sayName();//wutao b.sayName();//www实例b拥有父类Body的方法sayName b.saySex();//mail实例b拥有自己定义的方法saySex
2.借用构造函数(call&apply),也可以理解为组合式继承
call:
functionPerson(name){ this.name=name; this.sayHello=function(){ console.log(this.name); } } functionSon(name,age){ Person.call(this,name,age);//call用法:将this指针指向父类构造函数,并依次传入参数,使其拥有父类的属性和方法 this.age=age; this.sayFunc=function(){ console.log(this.name+"-"+this.age); } } vara=newPerson('wutao'); varb=newSon("wwwwww",22); a.sayHello();//wutao b.sayHello();//wwwwww;通过call继承来的父类Person的方法sayHello b.sayFunc();//wwwwww-22
apply:
functionPerson(name){ this.name=name; this.sayHello=function(){ console.log(this.name); } } functionSon(name,age){ Person.apply(this,[name,age]);//apply用法:类似call,将this指针指向父类构造函数,并传入一个由参数组成的数组参数,使其拥有父类的属性和方法 this.age=age; this.sayFunc=function(){ console.log(this.name+"-"+this.age); } } vara=newPerson('wutao'); varb=newSon("ttt",222); a.sayHello();//wutao b.sayHello();//ttt;通过apply继承来的父类Person的方法sayHello b.sayFunc();//ttt-222
js最主要的继承方法就这2种,当然,还有几种继承方法,但是有些继承方式在创建了实例之后,修改实例方法和属性会直接修改原型的方法和属性,那这样的继承就显得意义不大了,除非是业务有类似的需求才会去用到。
以上就是关于JavaScript继承方式的详细介绍,希望对大家的学习有所帮助。