为什么`this`不能在ES6箭头功能中工作? [英] Why is `this` not working in an ES6 arrow function?

查看:66
本文介绍了为什么`this`不能在ES6箭头功能中工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

'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?

推荐答案

箭头功能可以保存这个在创建函数时创建的闭包中。所以它没有将这个设置为函数调用的上下文。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆