How should I think of property definitions in obje

2019-08-01 07:25发布

问题:

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

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();

回答1:

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();

and with the arrow function converted:

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

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.