箭头函数的值

Lio*_*cer 9 javascript ecmascript-6 arrow-functions

我想了解ECMAScript 6中的箭头功能.

这是我在阅读时遇到的定义:

箭头函数具有隐式this绑定,这意味着this箭头函数内部值的值与this定义箭头函数的范围中的值相同!

根据定义,我相信this一个arrow function应该包含箭头函数定义的相同块级别值.

码:

var test = {
  id: "123123",
  k: {
    laptop: "ramen",
    testfunc: () => console.log(this)
  }
}

console.log(test.k.testfunc);
Run Code Online (Sandbox Code Playgroud)

但是,我从代码中得到了这个结果

function testfunc() {
    return console.log(undefined);
}
Run Code Online (Sandbox Code Playgroud)

我以为我会得到的输出是:

{"laptop": "ramen"}
Run Code Online (Sandbox Code Playgroud)

如果我跑了

console.log(test.k.testfunc());

elc*_*nrs 5

让我们转换成等效的 ES5 代码:

var test = {
  id: "123123",
  k: {
    laptop: "ramen",
    testfunc: function(){return console.log(this)}.bind(this)
  }
}
Run Code Online (Sandbox Code Playgroud)

请记住,这this取决于您如何调用该函数。外部this不在函数内部,因此默认为undefined严格模式。

简化场景如下:

console.log(this) // undefined

var test = {
  a: this // same `this` as above
}
Run Code Online (Sandbox Code Playgroud)