对象文字中的属性定义应该如何思考? [英] How should I think of property definitions in object literals?

查看:86
本文介绍了对象文字中的属性定义应该如何思考?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

let o = {
  x: 1,
  foo() {
    setTimeout(()=> 
      console.log(this.x),
    100);
  }
}
o.foo();

在100ms后打印出1。

This prints out 1 after 100ms.

这个绑定的箭头函数可以起作用吗?

Is this because it is equivalent to the following, meaning that the lexical this binding of arrow functions works?

let o = new (function Object() {
          this.x = 1;
          this.foo = ()=> console.log(this.x);
        });
o.foo();


推荐答案


相当于以下内容,这意味着这个绑定箭头功能的词法可以起作用?

Is this because it is equivalent to the following, meaning that the lexical this binding of arrow functions works?

不,比这简单得多。相当于

No, it's much simpler than that. It's equivalent to

var o = {
  x: 1,
  foo: function() {
    setTimeout(()=> 
      console.log(this.x),
    100);
  }
};
o.foo();

并转换箭头函数:

var o = {
  x: 1,
  foo: function() {
    var self = this;
    setTimeout(function() {
      console.log(self.x)
    }, 100);
  }
};
o.foo();

由于您正在调用 o.foo() c 因为箭头函数的这个受到词汇范围的约束,它访问 foo / code>。

Since you are calling o.foo(), this inside foo refers to o. Because an arrow function's this is subject to lexical scope, it access foo's this.

这篇关于对象文字中的属性定义应该如何思考?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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