This code works...It creates a Test
object and when that Test
object is initialized, InnerObject
is created and pushed into objects
array.
list()
method returns copy of objects
array.
I log return value of list()
method on line 42
and below it, on line 46
, I update the object in objects
array (mutating it).
What I don't understand is why this mutation is reflected on line 42
when this line should be executed before line 46
.
var Test = (function() {
var objects = [];
var InnerObject = {
init: function(data) {
this.prop1 = data.prop1 || 'first';
this.prop2 = data.prop2 || 'second';
this.prop3 = data.prop3 || 'third';
return this;
}
};
return {
init: function(data) {
data.forEach(function (item) {
var obj = Object.create(InnerObject).init(item);
objects.push(obj);
});
return this;
},
update: function(idx) {
var testObj = objects[idx];
for (var prop in testObj) {
testObj[prop] = '1';
}
return obj;
},
list: function() {
return objects.slice();
}
}
})();
var item = {
prop1: 'newFirst',
prop2: 'newSecond',
prop3: 'newThird'
}
var data = [item];
var obj = Object.create(Test).init(data);
console.log(obj.list()); // why the property value of each element here is 1
//when we are invoking update method below
//without update method it would log values
// newFirst and so on...
obj.update(0);