js 继承

原型继承
  • 说明:将子类的原型设置为父类实例
  • 缺点:
    • 子类new出来的实例,父类的属性没有隔离,会相互影响,引用同一地址;
    • 子类不能向父类传参数
function Parent() {
   this.name = 'parent' 
}

Parent.prototype.getName = function() { 
    console.log(this.name)
}

function Child() {
    this.name = 'child'
}

Child.prototype = new Parent() // 原型继承核心代码

let child = new Child()
构造函数继承
  • 说明:使用call()方法继承,子类继承父类的属性和方法, 子类能向父类传参数
  • 缺点:不能继承父类的原型属性和原型方法
function Parent() {
    this.name = 'parent' 
}

Parent.prototype.getName = function() { 
    console.log(this.name)
}

function Child() {
    Parent.call(this)
    this.name = 'child'
}

let child = new Child()
组合式继承
  • 组合上面的构造函数与原型继承的功能;
  • 缺点:call()方法已经拿到父类所有的属性 ,后面再使用原型时也会有父类所有属性;没有解决引用同一地址问题
function Parent() {
   this.name = 'Parent' 
}

Parent.prototype.getName = function() { 
    console.log(this.name)
}

function Child(value) {
    Parent.call(this) // 构造函数继承
    this.name = 'Child'
}

Child.prototype = new Parent() // 原型继承

let child = new Child()
寄生组合继承
  • 使用借用构造函数(call)来继承父类this声明的属性/方法
  • 设置子类prototype原型为父类prototype,来继承父类的prototype声明的属性/方法
  • (注意) 子类原型的constructor指向子类
function Parent() {
    this.name = 'parent'
}

Parent.prototype.getName = function() { 
    console.log(this.name)
}

function Child() {
    Parent.call(this)
    this.name = 'child
}

Child.prototype = Parent.prototype
// Child.prototype = Object.create(Parent.prototype)
Child.prototype.contructor = Child

let child = new Child()
es6 类继承
  • 使用寄生组合的方式实现
class Parent {
    contructor() {
        this.name = 'parent'
    }
    
    getName() {
        console.log(this.name)
    }
}

class Child extends Parent {
    contrucotr() {
        super()
        this.name = 'child'
    }
}

let child = new Child()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值