最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to disable pointers usage in JS? - Stack Overflow

programmeradmin2浏览0评论

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
Add a ment  | 

4 Answers 4

Reset to default 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++;

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...

发布评论

评论列表(0)

  1. 暂无评论