NodeJS中的ES6:对象文字中的箭头函数,返回的“this”值是多少? [英] ES6 in NodeJS: Arrow functions in object literal, what is the returned 'this' value?

查看:136
本文介绍了NodeJS中的ES6:对象文字中的箭头函数,返回的“this”值是多少?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用箭头功能,并尝试将它们作为对象字面值的属性,如下所示:

  var obj = {
a:()=> {
return this;
},
b:function(){
return this;
},
};

但是,当我测试这个,我不能完全解释什么是 的console.log(obj.a()); // => {}
console.log(obj.b()); // => {a:[功能],b:[功能]}

obj 的原型?

解决方案

很可能这将引用nodejs 默认对象(相当于窗口)。根据您的对象的放置范围,它可能被定义为其他东西。



如果您有使用strict 在您的项目中,这将是未定义的。


I am just playing around with arrow functions, and tried using them as a property in an object literal, like so:

var obj = {
  a: () => {
    return this;
  },
  b: function () {
    return this;
  },
};

But, when I test this, I can't quite explain what the this returned from obj.a() is.

console.log(obj.a()); //=> {}
console.log(obj.b()); //=> { a: [Function], b: [Function] }

Is it obj's prototype?

解决方案

Most likely this will refer to the nodejs default object (the equivalent of window). It may be defined as something else depending on what scope your object is placed in.

If you have use strict in your project this will be undefined.

这篇关于NodeJS中的ES6:对象文字中的箭头函数,返回的“this”值是多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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