0

I am having some trouble with scoping for a project I was working and was able to generalize the problem as follows.

I have a list of objects that I want to iterate through using a foreach loop and pass into a helper function. In the helper function I want to have a locally scoped version of the object to operate on with out modifying the original object.

I understand that functions in javascript pass objects by reference but it should possible to locally scope the reference.

Does anyone have any as to what I am doing wrong? Is there a way to do this without cloning the object. I'd prefer not to have to rebuild each object since the objects are quite big and performance is important.

var gloabalList = [{n:0},{n:0},{n:0}];
var output = [];
gloabalList.forEach((item,index)=>{
    gloabalList[index].n = index;
    //at this point the value n is the index
    messUpItem(item);    
    //at this point n is 2 we want it to be the index
    output.push(item.n);
});

//we want this to be (1,2,3) but it is returning (2,2,2)
alert(output);

function messUpItem(item){
    var x = item;// this should copy object val but its grabbing a reference
    x.n = 2;
    return item;
}

jsfiddle

Ari
  • 563
  • 2
  • 17
  • Hi Patrick thanks for the quick response I am aware that i can clone objects but that is not a good solution here since the objects could be quite big and performance is an issue. Is there a way to modify an object in local scope without cloning it? – Ari Mar 04 '17 at 10:37
  • 3
    You can do an [`Object.freeze(object)`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze) to freeze the properties from changes. 2 caveats though: 1. it does not freeze any objects that the properties might contain. Eg, `{a:1,b:{c:2}}`, here even if you called `Object.freeze()` you could still do `a.b.c = 3`. But you could do a deep freeze, iterating all properties and sub properties freezing each object. 2. You cannot unfreeze it – Patrick Evans Mar 04 '17 at 10:44

0 Answers0