0

Can someone explain why if I add a property to foo, somehow bar also inherits that property when I do this:

var foo = bar = {};
foo.hi = 'hi';

console.log(bar); //Object {hi: "hi"}

How does this work? I'm setting properties on foo, not bar. I realized I passed the object to bar and then bar to foo, but I must be missing something here.

Integer assignment works differently and more sense (to me anyhow):

var foo = bar = 5;
foo = 4;

console.log(bar); // 5
doremi
  • 14,921
  • 30
  • 93
  • 148

2 Answers2

1

Objects are passed by reference in JavaScript. Strings and number literals are not. In your code foo === bar, is the same object. You can simply declare the variables separately:

// Two different object instances
var foo = {};
var baz = {};
elclanrs
  • 92,861
  • 21
  • 134
  • 171
  • This appears to be the same with PHP. Is this common? What other langs do this if you know? – doremi Nov 25 '13 at 03:27
  • PHP is the same with Std Classes AFAIK. – elclanrs Nov 25 '13 at 03:31
  • @doremi PHP has made its behavior more consistent in this regard in recent versions. php 4, for instance a lot more times an object was passed as a copy vs a reference, necessitating use of the & modifier to force pass by reference. Anyway, to answer your question Python works similarly to JS in this way. Also, ruby: http://stackoverflow.com/questions/1872110/is-ruby-pass-by-reference-or-by-value – JAL Nov 25 '13 at 03:39
1

by doing foo = bar = {};, foo and bar are pointers to same object. so when you do:

foo.hi = 'hi';

It sets bar.hi also, because foo and bar point to the same object. To make it different, you should do:

var foo = {},  bar = {};
foo.hi = 'hi';
Sudhir Bastakoti
  • 99,167
  • 15
  • 158
  • 162