为什么`this`在ES6的箭头功能中不起作用?

Bla*_*mba 7 javascript ecmascript-6

这是我的代码:

'use strict';

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

但输出是:hello, undefined.

我希望输出是:hello, Hans Gruber.

我想我还没有理解this箭头功能?谁能给我一个明确的解释?

Bar*_*mar 7

箭头函数保存在this创建函数时创建的闭包中的绑定.所以它没有设置this调用函数的上下文.

在你的情况下,this注定要window当您创建的对象,所以this.usernamewindow.username不是obj.username.

文档:

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