为什么“这”在ES6的箭头功能上不起作用? [英] why the `this` is not work in arrow function of ES6?
问题描述
这是我的代码:
'use strict';
let obj = {
username : 'Hans Gruber',
hello: () => 'hello, ' + this.username
};
console.log(obj.hello());
但输出是: hello,undefined
我希望输出是: hello,Hans Gruber
。
我想我没有理解这个
在箭头功能?谁能给我一个明确的解释?
I think i have not understanding this
in arrow function? who can give me a clear explantion?
推荐答案
一个箭头函数保存这个$在创建函数时创建的闭包中的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.
在你的情况下, code>这个被绑定到窗口
当你创建对象,所以 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
这篇关于为什么“这”在ES6的箭头功能上不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!