Recent submissions

Comment · 9 years ago
Comment · 9 years ago

    var 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.

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton