javascript - 箭头函数的 this 值

标签 javascript ecmascript-6 arrow-functions

<分区>

我正在尝试理解 ECMAScript 6 中的箭头函数。

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

Arrow functions have implicit this binding, which means that the value of the this value inside of an arrow function is aways the same as the value of this in the scope in which the arrow function is defined!

根据定义,我认为 arrow functionthis 应该包含与箭头函数定义相同的 block 级值。

代码:

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

console.log(test.k.testfunc);

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

function testfunc() {
    return console.log(undefined);
}

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

{"laptop": "ramen"}

如果我运行这个

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

最佳答案

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

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

请记住,this 取决于您调用该函数的方式。外部 this 不在函数内部,因此在严格模式下它将默认为 undefined

下面的简化场景:

console.log(this) // undefined

var test = {
  a: this // same `this` as above
}

关于javascript - 箭头函数的 this 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31647507/

相关文章:

javascript - 选中复选框,然后输入到新行

javascript - 错误 : Can't find npm module 'moment'

JavaScript 生成器、函数* 和数组方法 forEach

javascript - 将项目数据传递给 react 模态

reactjs - Firebase 身份验证和 React Hook - 从钩子(Hook)返回的函数不起作用

javascript - 使用 Jquery 解析 XML

javascript - 在没有类的情况下使用 componentWillMount

javascript - 如何将 Handlebars 中的字符串解析为 html

javascript - 箭头函数是否像命名函数一样进行了优化?

javascript - 语法错误 : invalid arrow-function arguments (parentheses around the arrow-function may help)