JavaScript 的六种继承方式

原型链继承

function Parent() {
  this.name = 'Harry'
  // arr 被所有实例化对象共享
  this.arr = [1, 2, 3]
}
Parent.prototype.sayName = function () {
  console.log(this.name)
}

// 创建 Child 实例时,不能向 Parent 传参
function Child() {}
Child.prototype = new Parent()

借用构造函数继承

function Parent(name) {
  this.name = name
  this.arr = [1, 2, 3]
  /*
  	对象的方法需要写在构造函数内部
  	导致每次 new 产生新的实例时都需要创建方法
  */
}
// 对于 Child 来说,原型上的方法不可见
Parent.prototype.sayName = function() {
  console.log(this.name)
}

// 可以向 Parent 传参
function Child(name) {
  Parent.call(this, name)
}

组合继承

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

function Child(name, age) {
  Parent.call(this, name)
  this.age = age
}
Child.prototype = new Parent()
// 修改 Child 构造函数的指向*
Child.prototype.constructor = Child

原型式继承

function createObj(o) {
  function F() {}
  F.prototype = o

  return new F()
}

寄生式继承

function createObj(o) {
  var clone = Object.create(o)
  clone.sayHi = function() {
    console.log('Hi')
  }

  return clone
}

寄生组合式继承

function inheritPrototype (subType, superType) {
	var prototype = Object.create(superType.prototype)
	prototype.constructor = subType
	subType.prototype = prototype
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值