js的几种继承方式

前提call与apply

apply与call都能劫持另外一个对象的方法,继承另外一个对象的属性
apply(obj,[]) call(obj,params)
obj:这个obj对象将替换function中的this对象
apply另外一个参数为数组,call另外一个参数为参数列表,下面就是使用例子

 function Person(name,age)  
{  
    this.name=name;  
    this.age=age;  
}  

function Student(name,age,grade)  
{  
    //Person.apply(this,[name,age,grade]);  
    Person.call(this,name,age,grade);
    this.grade=grade;  
}  
//创建一个学生类  
var student=new Student("zhangsan",21,"一年级");  
//测试  
console.log("name:"+student.name+"\n"+"age:"+student.age+"\n"+"grade:"+student.grade);   

第一种方式 prototype

基本思想:利用原型让一个引用类型继承另外一个引用类型的属性和方法。
构造函数,原型,实例之间的关系:每个构造函数都有一个原型对象,原型对象包含一个指向构造函数的指针,而实例都包含一个指向原型对象的内部指针。

//父类  
function person(){  
    this.hair = 'black';  
    this.eye = 'black';  
    this.skin = 'yellow';  
    this.view = function(){  
        return this.hair + ',' + this.eye + ',' + this.skin;  
    }  
}  

//子类  
function man(){  
    this.feature = ['beard','strong'];  
}  

man.prototype = new person();  
var one = new man();  

console.log(one.feature); //['beard','strong']  
console.log(one.hair); //black  
console.log(one.eye); //black  
console.log(one.skin); //yellow  
console.log(one.view()); //black,black,yellow  

第二种方式 apply

基本思想:在子类型构造函数的内部调用超类构造函数,通过使用call()和apply()方法可以在新创建的对象上执行构造函数。

//父类  
function person(){  
    this.hair = 'black';  
    this.eye = 'black';  
    this.skin = 'yellow';  
    this.view = function(){  
        return this.hair + ',' + this.eye + ',' + this.skin;  
    }  
}  

//子类  
function man(){  
    // person.apply(this,new Array());  
    person.apply(this,[]);  
    this.feature = ['beard','strong'];  
}  

var one = new man();  

console.log(one.feature); //['beard','strong']  
console.log(one.hair); //black  
console.log(one.eye); //black  
console.log(one.skin); //yellow  
console.log(one.view()); //black,black,yellow  

第三种方式 call + prototype

基本思想:将原型链和借用构造函数的技术组合在一块,从而发挥两者之长的一种继承模式。

//父类  
function person(){  
    this.hair = 'black';  
    this.eye = 'black';  
    this.skin = 'yellow';  
    this.view = function(){  
        return this.hair + ',' + this.eye + ',' + this.skin;  
    }  
}  

//子类  
function man(){  
    // person.apply(this,new Array());  
    person.call(this,[]);  
    this.feature = ['beard','strong'];  
}  

man.prototype = new person();  
var one = new man();  

console.log(one.feature); //['beard','strong']  
console.log(one.hair); //black  
console.log(one.eye); //black  
console.log(one.skin); //yellow  
console.log(one.view()); //black,black,yellow  
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值