4

I just found out the hard way objects are passed by reference in Javascript, for example:

for(var layer = 0; layer < hudLayers['layers'].length; layer++){

    // Store the to-be-calculated values in this object
    var tempValues = hudLayers['layers'][layer];

    tempValues['name'] = 'test';
}

This will change the value in tempValues and hudLayers. (Seems kind of obvious, but a post without a bit of code seems so naked.)

Is there a quick way around this?

Jelle De Loecker
  • 20,999
  • 27
  • 100
  • 142
  • 1
    You want to assign a value to `tempValues` and have it not reflected in the `hudLayers`? Why would you want that? – Abhinav Sarkar Jul 19 '10 at 19:30
  • You really want to know? :) `hudLayers` contains several variables of image widths and heights. It's a HUD, so it has to be drawn multiple times per second. What's in `hudLayers` is actually the "blueprint" (base the width of this image on the value of that variable, ...) If I simply write that back to `hudLayers`the blueprint is gone and the image on screen will always stay the same. – Jelle De Loecker Jul 19 '10 at 19:53

3 Answers3

6

This is not an example of passing by reference (you aren't passing any parameters). However, you're correct; assigning an object will not make a deep copy.

You can make a deep copy of an object like this:

function deepCopy(obj) {
    if (typeof obj !== "object") return obj;
    if (obj.constructor === RegExp) return obj;

    var retVal = new obj.constructor();
    for (var key in obj) {
        if (!obj.hasOwnProperty(key)) continue;
        retVal[key] = deepCopy(obj[key]);
    }
    return retVal;
}

Note that if an object's constructor has any side-effects, this code will trigger them.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
0

There is no pass by reference in JavaScript. Objects are accessed through references and those references are assigned or passed passed by value, just like in Java

newacct
  • 119,665
  • 29
  • 163
  • 224
-1

Making a deep copy of an object is as simple as objCopy = obj.toSource();.

.toSource on MDN

kapa
  • 77,694
  • 21
  • 158
  • 175
tcaud
  • 1