Javascript multiple assignment clarification?
Looking at var a=b=1;
, I already know that both a
and b
has the same value.
But my question is :
Does the a
gets its value from 1
or from b
?
I made a small test :
/*1*/ (function (){
/*2*/ var j = window.j = function (){ alert('3');};
/*3*/ window.j2 = j;
/*4*/ })();
/*5*/
/*6*/ window.j(); //3
/*7*/ window.j=null;
/*8*/ window.j2();//3
As you can see line #8 yields 3
so I persume that a
is not having the value of b
but the value of 1
.
Am I right ?
visualize :
(function (){
var j = window.j = function (){ alert('3');};
|
| ^ ^
| | | //which one ?
+----------+--------+
})();
Assignment in javascript works from right to left. So you are getting your value from window.j
. Re-setting window.j
will not affect the result because Javascript variables always passes by value, exception is array or object.
Example of passing value by ref in JS object:
var obj = { x: 2 };
var anotherObj = obj;
anotherObj.x++;
alert(obj.x); //3
You can find more information here.
More useful examples available in this answer.
The "=" operator associates to the right so "a=b=1" is equivalent to "a=(b=1)". So 1 is assigned to b first with a result of 1, which is then assigned to a.
Assigment in JavaScript is right associative, so you are correct. In
a = b = c;
a
takes the value of b
at time of assignment, so if b
is later assigned to something else, a
retains its value (which happens to be the same as c
)
上一篇: 赋值运算符在一个语句中
下一篇: Javascript多重任务说明?