这是我的代码:
'use strict';
let obj = {
username : 'Hans Gruber',
hello: () => 'hello, ' + this.username
};
console.log(obj.hello());
但是输出是:hello, undefined
。
我希望输出为:hello, Hans Gruber
。
我想我对this
箭头功能还不了解。谁能给我一个清晰的解释?
箭头函数将的绑定保存在this
创建函数时创建的闭包中。因此,它不会设置this
为函数调用的上下文。
在你的情况下,this
注定要window
当您创建的对象,所以this.username
是window.username
不是obj.username
。
从文档中:
箭头函数表达式(也称为胖箭头函数)的语法比函数表达式短,并且按词法绑定
this
值
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句