James Andino
James Andino

Reputation: 25779

JavaScript understanding certain closure behaviors

The out put is 12 12 for the following code.

var omg = function(){

        var space = {q:12} ;

        var sq = [];

        sq[0] = function(){
                console.log(space.q);
                space.q = 14;
        };

        sq[1] = function(){
                console.log(space.q);
        };



        return sq;

};

omg()[0]();
omg()[1]();
~                           

Why is the output not 12 14 ?!?

Upvotes: 2

Views: 60

Answers (3)

Didier Ghys
Didier Ghys

Reputation: 30666

You execute two times the omg() so you get two different closures with separate space object.

Upvotes: 1

naivists
naivists

Reputation: 33511

Each omg() call returns a new function. Hence, the omg()[0]() call changes the local value of q of that particular instance. I think if you did it like this:

var a = omg()
a[0](); 
a[1](); 

you'd get the expected output.

Upvotes: 4

SLaks
SLaks

Reputation: 887405

Each omg() generates a separate closure with a separate space object.

To get your expected behavior, you need to call omg() once and call both functions in it using the same variable:

var arr = omg();
arr[0]();
arr[1]();

Upvotes: 3

Related Questions