Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning an Javascript Object's property by Value NOT Reference

So I have a class foo that has a method which returns an array bar. I have another function that calls foo.getBar and then filters the array. I want to be able to always get the original contents of bar when I use a different filter, but bing seems to be just creating a reference to bar, not a separate array. I have tried using return this.bar.valueOf(); in my function foo, still not working. When I remove items from bing they are also removed from bar. Someone please enlighten me on creating a unique array instead of a reference.

function foo(x, y, z){

    this.bar = new Array();
    ...
    this.bar = [ some , stuff , in , bar ];

    this.getBar = function getBar(){
        return this.bar;    
    }
    ...
}

var FooObject = new foo(x,y,z);

function baz(){

    var bing = FooObject.getBar();

    bing.splice(remove some pieces of the array);
}
like image 339
Jesse Avatar asked Sep 24 '26 10:09

Jesse


2 Answers

The easiest (and as far as I know, fastest) way to get a copy of an array is to use the slice method. Without any arguments, it defaults to array.slice(0, array.length), so it will copy the entire array.

Your getBar function would look like this:

this.getBar = function getBar(){
    return this.bar.slice();        
}

Note that this is a shallow copy, so any changes to the objects in the array will affect the original (adding and removing items won't affect it though).

like image 137
Matthew Crumley Avatar answered Sep 25 '26 22:09

Matthew Crumley


For objects, use the clone method:

function cloneObject(source) {
    for (i in source) {
        if (typeof source[i] == 'source') {
            this[i] = new cloneObject(source[i]);
        }
        else {
            this[i] = source[i];
        }
    }
}

var obj1= {bla:'blabla',foo:'foofoo',etc:'etc'};

var obj2= new cloneObject(obj1);
like image 36
Rodolfo Jorge Nemer Nogueira Avatar answered Sep 26 '26 00:09

Rodolfo Jorge Nemer Nogueira



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!