js实现继承中call的作用

183 阅读1分钟

我们实现一个ES5继承的时候,通常写法如下:

function parent() {
  this.name = 'parents'
}
function children() {
  parent.call(this)
  this.type = 'children'
}
children.prototype = Object.create(parent.prototype)
children.prototype.constructor = children3

不知道大家有没有思考过「 children」中「parent.call(this)」 的作用呢?为什么在children中调用call会给children添加name属性呢?

这个问题困扰了我好久,直到最近才豁然开朗。我们都知道call方法会改变this的指向,并立即执行改变后的方法,因此:

function children() {
  parent.call(this)
  this.type = 'children'
}

类似将parent内的this指向children内的this,相当于如下:

function children() {
  function parent() {
      this.name = 'parents'
    }
    parent()
  this.type = 'children'
}

转化为:

function children() {
  this.name = 'parents'
  this.type = 'children'
}

因此实现了parent内部的继承