javascript - Assignment associativity -
this question has answer here:
the assignment operator has right-to-left associativity.
var x,y; x=y=1;   works expected , x equals 1. consider code:
var foo={}; foo.x = foo = {n: 2};   i expect above work following:
var foo = {n: 2};  foo.x=foo;   however, in first case foo.x undefined while in second case foo.x points foo (circular reference). explanation?
javascript evaluates expressions left right. can show what's going on using additional variable:
var foo = {}; var bar = foo;  // keep reference object stored in foo foo.x = foo = {n: 2};   because of associativity, last statement parsed as:
foo.x = (foo = {n: 2});   but because of evaluation order, foo.x runs first (determining store value), foo, {n: 2}. store {n: 2} in variable foo, assign same value property x of old contents of foo ... can see looking @ bar:
foo = {"n" : 2} bar = {"x" : {"n" : 2 }}      
Comments
Post a Comment