为什么下面的代码在第42行上调用更新方法时在第42行记录变异对象。 [英] Why the code below logs mutated object on line 42 when update method is called below it, on line 46.

查看:63
本文介绍了为什么下面的代码在第42行上调用更新方法时在第42行记录变异对象。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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);





我尝试过:



此代码有效...它创建一个Test对象,当初始化Test对象时,创建InnerObject并将其推送到对象数组中。



list()方法返回对象数组的副本。



我记录第42行及其下面的list()方法的返回值,第46行,我更新对象数组中的对象(改变它)。



我不明白为什么这个突变反映在第42行应该执行这一行的原因第46行之前。



What I have tried:

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.

推荐答案

根据这个 [ ^ ]

您的代码被正确执行但状态为在执行所有代码后获取对象。

所以javascript流程没有任何问题。确实,如果你用

更新代码
According to this[^]
your code gets executed correctly but state of you object is fetched after all code is executed.
So there is nothing wrong with javascript flow here. And indeed if you'll update your code with
console.log(obj.list()[0].prop1) //it is newFirst as expected
 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);



你会得到预期的结果,正如我在评论中所述


you'll get expected result as I've stated in the comment


这篇关于为什么下面的代码在第42行上调用更新方法时在第42行记录变异对象。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆