Function.prototype.call does not set this at Arrow Function [duplicate]

老子叫甜甜 提交于 2019-12-12 12:47:33

问题


Note, Related Value of this inside object method?

Given

var obj = {
  property: 5,
  func1: function () {
    console.log(this.property);
  },
  func2: () => {
    console.log(this.property);
  }
}

this would be Window at obj.func2().

When tried setting this to obj using Function.prototype.call(), this was still Window

var obj = {
  property: 5,
  func1: function () {
    console.log(this.property);
  },
  func2: () => {
    console.log(this.property);
  }
}

obj.func2.call(obj);
  1. Is this expected behaviour?

  2. Why does Function.prototype.call() not set the context of obj.func2 to obj?


回答1:


It is expected as per the standard

An ArrowFunction does not define local bindings for arguments, super, this, or new.target. Any reference to arguments, super, this, or new.target within an ArrowFunction must resolve to a binding in a lexically enclosing environment.

That means - you cannot set something that is not defined.

Also, relevant:

The functions are called with the [[Call]] internal slot that sets the this binding as

  1. Perform OrdinaryCallBindThis(F, calleeContext, thisArgument).

Which in turn checks

  1. Let thisMode be the value of F’s [[ThisMode]] internal slot.
  2. If thisMode is lexical, return NormalCompletion(undefined).

So, internally it has an additional check on whether the function is lexically scoped (an arrow function) or not.

References:

  • 14.2.16 Runtime Semantics: Evaluation
  • 9.2.1 [[Call]] ( thisArgument, argumentsList)
  • 9.2.1.2 OrdinaryCallBindThis ( F, calleeContext, thisArgument )


来源:https://stackoverflow.com/questions/38557902/function-prototype-call-does-not-set-this-at-arrow-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!