How Should I Think Of Property Definitions In Object Literals?
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 foll
Solution 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.
Post a Comment for "How Should I Think Of Property Definitions In Object Literals?"