js-5种继承方式

1.原型链继承

–>通过原型链,继承属性和方法

function SuperType () {
  this.colors = ['pink', 'blue']
  this.name = 'qrq'
} 
SuperType.prototype.getName = function () {
  return this.name
}
function SubType() {
  this.age = '20'
}
SubType.prototype = new SuperType()
SubType.prototype.getAge = function() {
  console.log(this.age)
}
SubType.prototype.constructor = SubType //更改constructor指向

let instance1 = new SubType()
instance1.colors.push('yello')
instance1.getName() //'qrq'
instance1.colors // ['pink', 'blue', 'yello']

let instance2 = new SubType()
instance2.colors // ['pink', 'blue', 'yello']

  • 缺点:

1.通过原型链继承,原型会变成另一个类型的实例,该原型的引用类型属性被所有实例共享

2.在创建子类实例时,没有办法在不影响所有对象实例的情况下给超类型的构造函数中传递函数

2.借用构造函数

  function SuperType (name) {
    this.colors = ['pink', 'blue']
    this.name = name
  }
  SuperType.prototype.say = function() {
    return this.name
  }
  function SubType(name) {
    SuperType.call(this, name)
  }
  let instance1 = new SubType('yxq')
  instance1.colors.push('yello') // ['pink', 'blue', 'yello']

  let instance2 = new SubType('ce')
  instance2.colors //['pink', 'blue']
  • 优点:

1.可以向超类传递参数

2.解决原型中包含引用类型值被所有实例共享的问题

  • 缺点:

1.方法都在构造函数中定义,函数无法复用

2.无法继承超类型定义的方法

3.组合继承

–> 通过原型链及构造函数实现继承

function SuperType (name) {
  this.colors = ['pink', 'blue']
  this.name = name
}
SuperType.prototype.say = function() {
  return this.name
}
function SubType(name) {
  SuperType.call(this, name)
}
SubType.prototype = new SuperType()
SubType.construtor = SubType
let instance1 = new SubType('yxq')
instance1.colors.push('yello') // ['pink', 'blue', 'yello']

let instance2 = new SubType('ce')
instance2.say() // ce
instance2.colors // ['pink', 'blue']
  • 优点:

1.可以向超类传递参数

2.解决原型中包含引用类型值被所有实例共享的问题

3.可以继承超类型定义的方法

  • 缺点:

1.会调用两次超类型构造函数:一次是在创建子类型原型的时候,另一次是在子类型构造函数内部。

4.原型继承

–>是Object.create()的实现

function creatObj(o) {
  function F(){}
  F.prototype = o
  return new F()
}

5.class继承

  class Super{
    constructor (name) {
      this.name = name
    }
    sayName () {
      return this.name
    }
  }
  class SubType extends Super {
    constructor (name, age) {
      super(name)
      this.age = age
    }
    sayHi () {
      return super.sayName() + this.age + 'hi'
    }
  }
  let ins1 = new SubType('qrq', '20)
  ins1.sayHi() //qrq20hi
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值