gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 16:54:55 24 4
gpt4 key购买 nike

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

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

最佳答案

你可以在闭包的帮助下做到这一点:

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

关于javascript - 如何引用一个对象而不是复制它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32986670/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com