Aleksandr
Aleksandr

Reputation: 437

Loss of context. Closure

var user = {
    firstName: "Alex",
    sayHi: function() {
        alert(this.firstName);
    }
};

setTimeout(function() {
    user.sayHi(); // Alex
}, 1000);

They say that the user gets from the closure.

Do I understand correctly that the method user.sayHi wrapped in a function that is declared in the global context, and that has access to the user object? This forms a closure?

Upvotes: 0

Views: 72

Answers (1)

user.sayHi() is wrapped in an anonymous function which is in the global scope`. This anonymous function creates a closure, though the closure is of no consequence in this case. Since the anonymous function is in the global scope, and the user in the global scope, the anonymous function has access to the user object.

Upvotes: 1

Related Questions