popClingwrap
popClingwrap

Reputation: 4217

Javascript Object scope

This is a simplification of something that I've come up against in a larger project so I hope it makes sense.

I have two Objects:

FirstObj = {
    data : [],

    init : function()
    {
        for(var a = 0; a < 20; a++)
        {
            this.data[a] = 1;
        }
    }
};


SecondObj = {
    init : function()
    {
        var cell = FirstObj.data[0];
        cell = 0;
    }   
};

I then call the two init methods and log the results:

(function(){
    FirstObj.init();
    SecondObj.init();
    console.log(FirstObj.data);
})()

Now, I was assuming - based on my basis in Actionscript - that the log would show an Array in which the first item is a 0 and the rest all 1 but the 0 does not seem to stick.

Why does the assignment of the 0 value not succeed here and yet works fine if, instead of cell = 0 I target directly at FirstObj.data[0] = 0.

I'm guessing this is a scope thing and I can work round it but I'm trying to get a proper understanding of how JS actually handles this stuff, especially when lumping code into Objects like this (as an aside, is this a good approach in peoples general opinion?).

Thank for any help.

Upvotes: 2

Views: 50

Answers (2)

Benjamin Gruenbaum
Benjamin Gruenbaum

Reputation: 276286

Numbers in JavaScript are something called primitive value types (alongside strings, booleans null and undefined).

This means, that when you do

var cell = FirstObj.data[0];

You're passing the value in FirstObj.data[0] and not a refernece to it.

What you're doing is like:

var x = 5;
var y = x; // y is now 5 
y = 4; // y is 4, x is still 5.

Of course, something like FirstObj.data[0] = 0 should work.

Upvotes: 1

Fr&#233;d&#233;ric Hamidi
Fr&#233;d&#233;ric Hamidi

Reputation: 262919

Array indexing returns values in Javascript, not references. It means that once data[0] is assigned to cell, further modification of cell will not affect data[0].

Assigning the array itself would result in the behavior you're looking for:

SecondObj = {
    init : function()
    {
        var cells = FirstObj.data;
        cells[0] = 0;  // Will also affect data[0].
    }   
};

Upvotes: 1

Related Questions