箭头功能和这个

Kis*_*tel 3 javascript ecmascript-6

我正在浏览Twitter,发现了以下推文:

https://twitter.com/_ericelliott/status/855598297939144704

这是推文中的代码:

const double = () => this.x * 2;
const numDouble = double.bind({ x: 5 });
numDouble();
Run Code Online (Sandbox Code Playgroud)

当您在控制台中运行此代码段时,它将生成NaN。怎么样?作者显式绑定x的值,但仍显示NaN。

作者还指定了箭头功能不能绑定此功能。据我所知,箭头功能在词法上绑定了这种形式的范围周围的值。那为什么作者这么宣称呢?

请澄清我的疑问,并在此先感谢您的帮助。

ibr*_*rir 5

箭头函数不绑定this。根据MDN:

没有约束力

在使用箭头函数之前,每个新函数都定义了自己的this值(在构造函数中为新对象,在严格模式函数调用中未定义,在函数称为“对象方法”的情况下为上下文对象,等等)。事实证明,这是一种面向对象的编程风格,令人讨厌。

因此,this在您的示例中将是全局对象window,该对象显然没有名为的属性x

例:

function foo() {
  let arrow = () => {
    console.log(this);     // will use foo's this as arrow will never have its own this
  }
  
  arrow.call({"x": "x"});  // ... even if we specify it using bind, call, or apply
}

foo.call({"y": "y"});      // specifying the this for foo (this value will eventually be used by arrow because it will be availbale in its scope)
Run Code Online (Sandbox Code Playgroud)