为什么“这”在ES6的箭头功能上不起作用? [英] why the `this` is not work in arrow function of ES6?

查看:104
本文介绍了为什么“这”在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?

推荐答案

一个箭头函数保存这个。所以它没有将这个设置为调用函数的上下文。

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

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