I would like an insight about my codes, what is going on behind the scene? I am new about JS Object prototype, i use to manipulate object but no really playing with prototype!
I have two scripts (JavaScript) as shown below:
// First script //
function MyObject(dim=3){
this.table= [];// 2D array
this.initialiseTable(dim);
this.setTable = function (index,symbol){
// i want to change only one element of my table
this.table[index[0]][index[1]]=symbol;
};
}
MyObject.prototype ={
initialiseTable:function(dim){
var array = [];
for (let i=0; i<dim; i++){
array.push("0");
}
for (let i=0; i<dim; i++){
this.table.push(array);
}
}
};
console.log("First script")
var O = new MyObject(6);
console.log(O.table);
O.setTable([1,3],"Changed");
console.log(O.table);
// Second script
// First script //
function MyNewObject(dim=3){
this.table= [];// 2D array
this.initialiseTable(dim);
this.setTable = function (index,symbol){
// i want to change only one element on my table
this.table[index[0]][index[1]]=symbol;
};
}
MyNewObject.prototype ={
initialiseTable:function(dim){
// i delete the array variable and implement something hard but then
// i don't have the flexibility to set freely the table dimension
for (let i=0; i<dim; i++){
this.table.push([0,0,0,0,0]);
}
}
};
console.log(" ");
console.log("Second script");
var OO = new MyNewObject(6);
console.log(OO.table);
OO.setTable([1,3],"Changed");
console.log(OO.table);
The difference between both codes is only in seTable definition. Now here is the table after setTable call on the O object (first script):
[ [ '0', '0', '0', 'Changed', '0', '0' ],
[ '0', '0', '0', 'Changed', '0', '0' ],
[ '0', '0', '0', 'Changed', '0', '0' ],
[ '0', '0', '0', 'Changed', '0', '0' ],
[ '0', '0', '0', 'Changed', '0', '0' ],
[ '0', '0', '0', 'Changed', '0', '0' ] ]
and here is the table after setTable call on the OO object:
[ [ 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 'Changed', 0, 0 ],
[ 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 0 ] ]
Why I get all the third element of each row change in the object table with the first script?