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
1

2 Answers 2

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 = {};
Sign up to request clarification or add additional context in comments.

3 Comments

This appears to be the same with PHP. Is this common? What other langs do this if you know?
PHP is the same with Std Classes AFAIK.
@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: stackoverflow.com/questions/1872110/…
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';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.