1

I have created a module that I use to write to a global array like so:

class SomeLibrary {

  constructor( product ) {
    if (typeof window.globalArray === 'undefined'){
        window.globalArray = [];
    }
    this._someVal = 0;
  }
  .
  .
  .
  addToGlobalArray( obj ) {
    obj.someVal = this._someVal;
    window.globalArray.push( obj );
    this._someVal++
  }
  .
  .
  .
  .
}

let someLib = new SomeLibrary();
someLib.addToGlobalArray({test: 'hello'})
someLib.addToGlobalArray({test: 'hello again'});

And want my 'globalArray's 'someVal' to use the current value of _someVal from the module not the reference for the result to look like:

//I want this outcome    
[
    {test: 'hello', someVal: 0},
    {test: 'hello again', someVal: 1}
]

Not (as it currently operates)

//I don't want this outcome    
[
    {test: 'hello', someVal: 1}, //someVal here is 1 as it is a reference to the current value of _someVal in the module
    {test: 'hello again', someVal: 1}
]

What do I need to do to pass the value and not the reference into the global Object?

(I don't have access to jQuery or Underscore)

Fraser
  • 14,036
  • 22
  • 73
  • 118

1 Answers1

1

Your code already works the way you say you want it to.

By definition, the property being added to the object being added to the global array is added by value (its value at that precise moment in time), not by reference; indeed, there is no way to do that in JS other than via things like "getters" or "proxies".

I suspect you are actually running something like the following code:

var object = {test: "hello"};
someLib.addToGlobalArray(object})

object.test = "hello again"; 
someLib.addToGlobalArray(object);

This would result in the single object {test: "hello again", someVal: 1} occupying both the first and second position in the global array. That fact that someVal has the same value of 1 in both globalArray[0] and globalArray[1] has nothing to do with some notion of it being set by reference; it is just because it's the same object in both slots.