“this”在另一个对象的“this” - javascript中访问

时间:2018-03-10 17:47:59

标签: javascript arrays object

考虑这个例子:

如果您要使用上面的代码并运行它,控制台消息将为100.当我将100添加到obj2的“this”中的位置时,为什么打印出100?我怎么做到这样obj2有自己独特的“这个”?另外请知道这是我的代码的简化示例,我不能只在obj2中创建一个包含所有内容的单独对象。

var obj1 = function() {
  this.obj2Arr = [];
  this.pos = {
    "x": 0,
    "y": 0
  };
  this.obj2Arr.push(new obj2(this.pos));
  console.log(this.pos.x);
  // Prints out 100 even though obj2 was where I added the 100 for it's "this".
  // Why does it do that, and how do I make obj2's "this" unique to it?
};

var obj2 = function(pos) {
  this.pos = pos;
  this.pos.x = this.pos.x + 100;
};

var example = new obj1();
console.log(example);

1 个答案:

答案 0 :(得分:3)

这是因为pos是一个对象,对象总是通过javascript中的引用传递。

要回答您的问题:使用Object.assign创建一个新对象:

var obj1 = function() {
  this.obj2Arr = [];
  this.pos = {
    "x": 0,
    "y": 0
  };
  this.obj2Arr.push(new obj2(Object.assign({}, this.pos)));
  console.log(this.pos.x);
};

var obj2 = function(pos) {
  this.pos = pos;
  this.pos.x = this.pos.x + 100;
};

var example = new obj1();
console.log(example);