I have a function within an object constructor that is altering all objects created by that constructor. I'm not sure why. Could someone please take a look at my code and tell me what I'm missing?
A quick description of what is going on:
Warning! It might be easier to just read through the code than try to make sense of my description
I have created two new Arrays. The first one called foos
, which will be an array of foo
objects each one containing an array of bar
objects. The second is called bars
which is an array of all bar
objects that are available to be added to the foos.foo.bars
arrays.
When a new foo
object is created using the foo
object constructor it is given two arguments(aBars,bBars
). aBars
is an array of all bar
objects to be included in the foo
object. bBars
is an array of all included bar
objects that are considered 'special' in some way. Within the constructor there is a function that runs through every object in the bars
array and if it's name value matches that of a string in the aBars
argument then it is added to foo.bars
array. If it's name value matches a string in the bBars
argument it then has it's property bBar
set to true, otherwise it's set to false.
The issue I'm having is that on the second foo
object constructor when a bar object has bBar set to true or false it also changes that value in that object in all other foo.bars
objects.
I realize that this is probably hard to follow. Sorry about that, it's the end of the day.
Found my own answer!
I just realized what the issue is. foos[0].bars[4]
and foos[1].bars[3]
are not separate objects, they are simply two different variables pointing to the same object. So when one is changed the change shows up on both. Wow, I can't believe I just spent so much time working on this when the answer was a basic fact about how javascript works that I learned back when I first started.
Ok, the new question:
How can I change this code to create duplicates of the objects instead of just pointing at the originals? This is not something I've ever had to do before.
Thanks
JS:
var foos = new Array();
var bars = new Array();
function foo(aBars,bBars) {
var $this = this;
this.aBars = aBars;
this.bars = new Array();
bars.forEach(function(e,i) {
if ($this.aBars.lastIndexOf(e.barName) > -1) {
$this.bars.push(e);
if (bBars.lastIndexOf(e.barName) > -1) {
$this.bars[$this.bars.length-1].bBar = true;
} else {
$this.bars[$this.bars.length-1].bBar = false;
}
}
});
}
function bar(name) {
this.barName = name;
}
bars.push(new bar('l'));
bars.push(new bar('m'));
bars.push(new bar('n'));
bars.push(new bar('o'));
bars.push(new bar('p'));
foos.push(new foo(['l','m','n','o','p'],['n','p']));
foos.push(new foo(['l','n','o'],['n','o']));
console.log(foos);