1

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);
Djole
  • 11
  • 1

2 Answers2

0

It might be because console.log() is executed asynchronously:

console.log() async or sync?

Reading from the answers there I suspect that's what's going on here. To rule out this as a problem to your actual code there's suggestion to force it being interpreted as it is at that moment: console.log(JSON.stringify(obj.list()))

user3647971
  • 1,069
  • 1
  • 6
  • 13
0

When I run this in either the browser console or in nodejs, the property values of the elements are behaving in the expected way that you said you're aiming for, i.e., they're not updating until after the call to update.

What type of environment are you running this in?

Jason Wilkes
  • 21
  • 1
  • 3