0

为什么是结果{"a":"b","c":1}

var foo = {"a":"b","c":0};
var bar = foo;
bar.c++;
alert(JSON.stringify(foo));

如何禁用此行为?

4

4 回答 4

4

Both foo and bar variables reference the same object. It doesn't matter which reference you use to modify that object.

You cannot disable that behaviour, this is how JavaScript and many other major languages work. All you can do is to clone the object explicitly.

var foo = {"a":"b","c":0};
var bar = {"a":foo.a, "c": foo.c};
bar.c++;
于 2012-04-25T15:42:38.753 回答
3

首先,Javascript 不传递指针,它传递引用,略有不同。其次,不幸的是,没有办法修改 Javascript 的默认行为

您可能想要做的是创建一个构造函数并使用它来创建一个对象的两个相似但独立的实例。

function Foo(a, b) {
    this.a = a;
    this.b = b;
}

var bar1 = new Foo(0, 0);
var bar2 = new Foo(0, 0);
bar2.b++;

console.log(bar1);
console.log(bar2);

>> {a:0, b:0};
>> {a:0, b:1};
于 2012-04-25T15:43:26.230 回答
3

您正在做的是对对象进行第二次引用,但您似乎想要的是该对象的副本

如果你想要那个功能,那么你真的想要一个复制函数,将所有属性一个一个地复制到一个新对象中:

// Take all the properties of 'obj' and copy them to a new object,
// then return that object
function copy(obj) {
  var a = {};
  for (var x in obj) a[x] = obj[x];
  return a;
}

var foo = {"a":"b","c":0};
var bar = copy(foo);
bar.c++;
alert(JSON.stringify(foo));

你会得到{"a":"b","c":0}

于 2012-04-25T15:47:30.457 回答
2

您不能禁用 javascript 的工作方式。

如果更改引用对象,它会影响所有对象引用...

于 2012-04-25T15:42:43.920 回答