admin管理员组文章数量:1393361
Why is the result {"a":"b","c":1}
?
var foo = {"a":"b","c":0};
var bar = foo;
bar.c++;
alert(JSON.stringify(foo));
How to disable this behavior?
Why is the result {"a":"b","c":1}
?
var foo = {"a":"b","c":0};
var bar = foo;
bar.c++;
alert(JSON.stringify(foo));
How to disable this behavior?
Share edited Apr 25, 2012 at 20:25 gdoron 150k59 gold badges302 silver badges371 bronze badges asked Apr 25, 2012 at 15:40 Danny FoxDanny Fox 40.8k29 gold badges71 silver badges96 bronze badges 4- What result are you expecting instead? – Richard Ev Commented Apr 25, 2012 at 15:42
- 3 possible duplicate of How to Deep clone in javascript – Quentin Commented Apr 25, 2012 at 15:44
- @Quentin. I'm not sure it's a duplicated, though it answer his question. – gdoron Commented Apr 25, 2012 at 15:46
- @Quentin: That may be how to answer this question, but it's not really a duplicate. – josh3736 Commented Apr 25, 2012 at 15:46
4 Answers
Reset to default 4Both 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++;
What you're doing is making a second reference to an object but what it seems you want is a copy of that object instead.
If you want that functionality then you really want a copy function that copies all of the properties, one by one, into a new object:
// 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));
and you'll get {"a":"b","c":0}
First, Javascript doesn't pass pointers, it passes references, slightly different. Secondly, there's no way to modify Javascript's default behavior, unfortunately fortunately.
What you might want to do is create a constructor and use that to create two similar, but separate instances of an object.
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};
You can't disable the way javascript works.
If you change a reference object, it effects all the object references...
本文标签: javascriptHow to disable pointers usage in JSStack Overflow
版权声明:本文标题:javascript - How to disable pointers usage in JS? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744653074a2617801.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论