Function.prototype.call 没有在箭头函数中设置这个

Function.prototype.call does not set this at Arrow Function

注意,相关

给定

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

this 将是 Windowobj.func2()

当尝试使用 Function.prototype.call()this 设置为 obj 时,this 仍然是 Window

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

obj.func2.call(obj);

  1. 这是预期的行为吗?

  2. 为什么Function.prototype.call()不设置context obj.func2obj?

预计按照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.

这意味着 - 您不能设置未定义的内容。

另外,相关的:

使用 [[Call]] 内部插槽调用函数,将 this 绑定设置为

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

这又是checks

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

因此,它在内部会额外检查函数是否在词法范围内(箭头函数)。

参考文献: