user2251919
user2251919

Reputation: 675

Object variable scope javascript?

I don't understand how this scope works. How does the value of eg.i get modified in first when it is only modified in second?

EXAMPLE

var obj = {

    first: function() {

        var eg = {i: 0}; // eg equals 0 here

        obj.second(eg);
        obj.second(eg);

        console.log(eg.i); // 2
    },

    second: function(eg) {

        ++eg.i;
    }
};

How does eg.i get modified in the first function as well?

Upvotes: 3

Views: 4196

Answers (3)

Zirak
Zirak

Reputation: 39808

As noted in my comment to Ahmed Nuaman's answer, saying that the argument is passed by reference is incorrect. Proving that is trivial:

function change (x) {
    //"replace" x with a different object?
    x = {
        a : 4
    };
}
var o = { a : 6 };
change(o);
console.log(o.a); //6

If the argument would truly have been passed by reference, o.a would have been 4. However, the argument is passed by the reference value - in this case, the value is simply and object.

And that's why you observed the symptoms presented in the question: When you directly modified the argument, the object passed in was changed.

It's as if you got some ice-cream, then went back to the stand to ask for an extra scoop of vanilla. You still have the same cup, but with that extra something. Using that analogy in the example above, you ask for a new vanilla ice-cream: you still have the old one, and that hasn't changed (well, it may have melted a bit). In a pass-by-reference scenario, you would've dumped your existing ice-cream, and got a brand new one.

As a final note: This is not about scoping rules in js. If eg wasn't passed to the second function, it would've been unavailable to it.

Upvotes: 4

Ahmed Nuaman
Ahmed Nuaman

Reputation: 13221

When objects are passed in to functions in JS, they're passed in as references rather than values: http://snook.ca/archives/javascript/javascript_pass

Upvotes: 4

Blender
Blender

Reputation: 298106

You're passing eg as a parameter to second. It might be easier to see if you renamed it:

second: function(x) {
    ++x.i;
}

It gets modified in the first function because you modify it with the second function.

Upvotes: 3

Related Questions