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