为什么`this`不能在ES6箭头功能中工作? [英] Why is `this` not working in an ES6 arrow function?
问题描述
这是我的代码:
'use strict';
let obj = {
username : 'Hans Gruber',
hello: () => 'hello, ' + this.username
};
console.log(obj.hello());
但输出为: hello,undefined
。
我希望输出为:你好,Hans Gruber
。
我想我还没有在箭头函数中理解这个
。谁可以给我一个明确的解释?
I think I have not understood this
in an arrow function. Who can give me a clear explanation?
推荐答案
箭头功能可以保存这个$的绑定c $ c>在创建函数时创建的闭包中。所以它没有将
这个
设置为函数调用的上下文。
An arrow function saves the binding of this
in the closure that's created when the function is created. So it doesn't set this
to the context of the call to the function.
在你的情况下,此
在创建对象时绑定到窗口
,因此 this.username
是 window.username
,而不是 obj.username
。
In your case, this
was bound to window
when you created the object, so this.username
is window.username
, not obj.username
.
来自文档:
箭头函数表达式(也称为胖箭头函数)与函数表达式相比语法更短,词法绑定
这个
价值
An arrow function expression (also known as fat arrow function) has a shorter syntax compared to function expressions and lexically binds the
this
value
这篇关于为什么`this`不能在ES6箭头功能中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!