Skip to content

手动实现ES6继承

仲灏2022-06-06约 1 分钟

借助构造函数实现

js
function parent1() {
  this.name = 'parent1'
}

function child1() {
  this.name = 'child1'
	this.age = 18
  
  // 继承this上下文
  parent1.call(this)
}

// 原型链继承

js
function parent2() {
  this.name = 'parent1'
}

function child2() {
  this.name = 'child1'
	this.age = 18
}


child1.prototype = new parent2()

共享了原型对象地址

组合方式解决

js

function parent3() {
  this.name = 'parent1'
}

function child3() {
  this.name = 'child1'
	this.age = 18
  
  parent3.call(this)
}

child3.prototype = new parent3()

缺点:重复实例化了 而且后面的原型链中方法用不着

child3.prototype = parent3.prototype

问题: 会导致实例的__proto__.constructor 指向parent3

child3.prototype = Object.create(parent3.prototype)

讨论区

欢迎留下想法与补充