Why do local variables that reference a global object seem to violate function scope?

I have this simple example() function. Now I've learned a little about function scope in javascript. But what baffles me is that local variables that refer to a global object, seem to violate function scope (or my understanding of it):

// https://jsfiddle.net/vnmscgsa/1/

var values = {
    'Extra level of nesting': {
        keyOne: 'one',
        keyTwo: 'two'    
    }
};

var example = function(values) {

    function setValue(value) {
      var data = values[value]; // a local copy of the values object
      data.keyOne = 'twenty'; // should only influence the local copy
    }

    for (var value in values) {
      setValue(value);
      console.log(values[value]);
    }

};

example(values); // will log "Object { keyOne: "twenty", keyTwo: "two" }"

I would say that the output of the example() function should be "Object { keyOne: "one", keyTwo: "two" }", because the data variable in the setValue function is scoped to that function (so a copy of the global object that doesn't have any influence on it).


The problem doesn't exist when referencing a string instead of an object: https://jsfiddle.net/gbyvh8t2/1/

Upvotes: 1

Views: 60

Answers (1)

Quentin
Quentin

Reputation: 943510

var data = values[value]; // a local copy of the values object

You are copying the value of values[value] to data.

That value is a reference to the object (because you only ever deal in references when accessing JavaScript objects).

You now have a local variable (data) and property (whatever values[value] resolves as) which each contain a reference to the same object.

The variables themselves are still in their original scopes. You've just passed a value between them.

Upvotes: 4

Related Questions