Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why the program's result is undefined?

Tags:

javascript

 var foo = {};
 foo.c = foo = {};
 console.log(foo.c);

why the result is undefined? i thought it is supposed to be '[object Object]'

like image 269
user1039304 Avatar asked Feb 24 '14 05:02

user1039304


1 Answers

Strange things are happening here in the assignments:

foo.c = (foo = {})

The reference to foo.c is resolved first and points to the old foo object, before the inner expression is evaluated where foo is re-assigned with the {} emtpy object literal. So your code is equivalent to

var foo1 = {};
var foo2 = {};
foo1.c = foo2;
console.log(foo2.c) // obviously undefined now

You can also try

var foo = {}, old = foo;
foo.c = foo = {};
console.log(old, foo, old.c===foo); // {c:{}}, {}, true
like image 135
Bergi Avatar answered Nov 07 '22 02:11

Bergi