如何引用一个对象而不是复制它?

时间:2015-10-07 07:53:20

标签: javascript

如何引用一个对象而不是复制它?如下面的代码所示,显然o2在调用o = 1时保持不变。如果我想在更改o2时更改o该怎么办?

var o = { 
  a: {
    b:2
  }
}; 
// 2 objects are created. One is referenced by the other as one of its property.
// The other is referenced by virtue of being assigned to the 'o' variable.
// Obviously, none can be garbage-collected


var o2 = o; // the 'o2' variable is the second thing that 
            // has a reference to the object
o = 1;      // now, the object that was originally in 'o' has a unique reference
            // embodied by the 'o2' variable

4 个答案:

答案 0 :(得分:2)

你可以在闭包的帮助下完成:

function Closure() {
    var o = { 
      a: {
        b:2
      }
    }; 

    this.getO = function () {
        return o;
    };
}

var closure = new Closure(),
    newO = closure.getO();
newO.a = 111;

console.dir(closure.getO());

答案 1 :(得分:1)

o不是对象,而只是一个引用。您刚刚将其重新分配给1,但您并未真正覆盖或更改先前引用的o对象。

答案 2 :(得分:1)

在javascript中,变量总是引用该对象。它们永远不会被复制。

这是你在做什么:

var o = { 
  a: {
    b:2
  }
}; 

创建一个新对象,'o'引用该对象。

var o2 = o;

现在o和o2都引用了你最初创建的同一个对象。

o = 1;

现在这里是棘手的部分。 在这里,您将数字1分配给'o'变量,该变量以前是指您创建的对象。 'o2'仍然指的是那个对象。 但是现在,'o'不再是指对象,它被强制为Number类型。 (简单来说,强制意味着类型转换)

答案 3 :(得分:1)

JS原始整数和字符串按值传递,而对象通过引用传递。

为了实现你想要的,你可以使用一个闭包:

var o = { 
  a: {
    b:2
  }
}; 

var o2 = function() { return o; }; 
o = 1; 
console.log(o2());