2

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.

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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].
    }   
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.