javascript实现继承的几种方式

function father(value){
    this.value=value;
}

father.prototype.getValue=function(){
    console.log(this.value)
}

function child(value){
    father.call(this,value)
}

child.prototype=new father;

var childOne=new child(1);

childOne.getValue();
//组合继承,缺点将所有父级的属性全部继承到子类的身上造成不必要的浪费

function parent(value){
    this.value=value;
}

parent.prototype.getValue=function(){
    console.log(this.value)
}
function childL(value){
    father.call(this,value)
}
childL.prototype=Object.create(parent.prototype,{
    constructor:{
        value:child,
        enumerable:false,
        configurable:true,
        writable:true
    }
})

var childTwo=new childL(2);
childTwo.getValue();
//组合寄生集成该继承方式与上面的方法不同,使用create创制造一个新的对象,集成父级原型对象。

class Parent{
    constructor(value){
        this.value=value
    }
    getValue(){
        console.log(this.value)
    }
}
class Child extends Parent{
    constructor(value){
        super(value)
        this.value=value;
    }
}
let childThree=new Child(3);
childThree.getValue()
//ES6继承方式,这种方式使用class这个语法糖,class的本质还是一个函数,super的作用在继承父类的时候调用该方法可以改变this的指向,相当于Parent.call(this,value)

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值