【问题标题】:Why is `this` not working in an ES6 arrow function? [duplicate]为什么 `this` 在 ES6 箭头函数中不起作用? [复制]
【发布时间】:2015-12-30 22:37:50
【问题描述】:

这是我的代码:

'use strict';

let obj = {
  username : 'Hans Gruber',
  hello: () => 'hello, ' + this.username
};
console.log(obj.hello());

但输出是:hello, undefined

我希望输出是:hello, Hans Gruber

我想我还没有理解箭头函数中的this。谁能给我一个清楚的解释?

【问题讨论】:

  • 这不是那个问题的重复。这是关于对象范围的
  • 我仍然很困惑,如果不了解 this 在箭头函数中的工作原理,你怎么能了解箭头函数。
  • 另外,请在提出新问题之前使用搜索。

标签: javascript ecmascript-6


【解决方案1】:

箭头函数将this 的绑定保存在创建函数时创建的闭包中。所以它不会将this 设置为函数调用的上下文。

在您的情况下,this 在您创建对象时绑定到window,因此this.usernamewindow.username,而不是obj.username

来自documentation

与函数表达式相比,箭头函数表达式(也称为胖箭头函数)的语法更短,并且在词法上绑定了this

【讨论】:

    【解决方案2】:

    箭头函数保留定义它的词法范围。因此,hello 函数中的 this 与定义函数时的 this 相同,而不是它作为属性的对象。它本质上是 ES5 的简写

    function() {
        return 'hello, ' + this.username;
    }.bind(this);
    

    你想要的是类似的东西

    let obj = {
        username: 'Hans Gruber',
        hello() {return `hello, ${this.username}`;}
    };
    

    【讨论】: