So I have a property in a class called 'tiles' which contains information about a checkers board game's state. I'm trying to push this property to an array called 'moves' every time I make a legal move and at the start of the game. But the problem is, every time I push the new tiles property, the previous elements in the moves array change to the values of the latest pushed tiles.
I understand this is happening because the object is being passed by reference and hence replaces old elements in array because they now point to the same object, which is the latest value of the property tiles. So with my code given below, is there a way I can push this object not by reference but each different individual state of 'tiles' that resulted due to legal moves.
Here is my snippet: App.js
App = function () {
var self = this;
self.tiles = [];
// this is populated with objects from a json file
//code to fetch json and save it to self.tiles
//more code
this.startGame = function () {
//other code
self.moves.push(self.tiles);
};
this.makeMove = function () {
//other code
self.moves.push(self.tiles);
};
};
So what I expect is in self.moves array, the tiles should point to different objects instead of the same object. It should contain different states of self.tiles but right now, as I push the property, the elements of 'moves' array is overwritten by the latest self.tiles value.
Any help to solve this problem will be highly appreciated. Thanks!