javascript - 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 because equivalent following, meaning lexical this binding of arrow functions works?

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

is because equivalent following, meaning lexical binding of arrow functions works?

no, it's simpler that. it's equivalent to

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

and arrow function converted:

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

since calling o.foo(), this inside foo refers o. because arrow function's this subject lexical scope, access foo's this.


Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -