3 ms·
Note: Arrow functions cannot help us when the function is defined on the object literal as it will resolve to the enclosing lexical scope, which in this case is
by twiss 10y ago
Note: Arrow functions cannot help us when the function is defined on the object literal as it will resolve to the enclosing lexical scope, which in this case is the global scope.
This is not true. With an arrow function, the example prints "Object Name". MDN says: "An arrow function does not create its own this context, so this has its original meaning from the enclosing context." [1]
(The "enclosing context" in this case refers to the context in which the arrow function was created, not the context in which the function in which the arrow function was created was created.)
[1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#No_binding_of_this https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
- sidthesloth 10y agovar name = "Global Name"; var obj = { name : 'Object Name', printName : function() { setTimeout(() => { console.log(this.name); }, 2000); } }; obj.printName(); //prints "Object Name" var printNameReference = obj.printName; printNameReference(); //prints "Global Name" You will see that "Global Name" will still be printed out. The reason is because arrow functions take the enclosing lexical scope, and the arrow function to setTimeout in the example is created each time the printName function is invoked. The printNameReference() invocation sets the scope of the printName function to global because of the way it is invoked and hence the arrow functions to setTimeout will also take this scope. Changing the printName function itself as arrow function does not help either. var obj = { name : 'Object Name', printName : () => { setTimeout(() => { console.log(this.name); }, 2000); } }; The above code will again set the printName function to the enclosing global scope, because that is where obj is declared.
- nawitus 10y agoIf you add "var that = this;" to printName function the printNameReference still doesn't work.