What is the outcome of: var myvar1 = myvar2 = myvar3?
I have seen in some nodejs scripts variables/objects being used like this:
var myvar1 = myvar2 = myvar3;
Why is this used and what does it mean?
This sets myvar2 to myvar3 , and sets myvar1 to myvar2 .
I assume myvar3 and myvar2 have been declared before this line. If not, myvar2 would be a global (as there's no var ), and if myvar3 wasn't defined, this would give an error.
This expands to:
myvar2 = myvar3; // Notice there's no "var" here
var myvar1 = myvar2;
It will evaluate to:
var myvar1 = myvar2 = myvar3;
var myvar1 = myvar3; // 'myvar2' has been set to 'myvar3' by now
myvar3; // 'myvar1' has been set to 'myvar3' by now
It will first assign myvar3 to myvar2 (without var , so possibly implicit global, watch out for that).
Then it will assign myvar3 's value to myvar1 , because the set value is returned.
The result is again returned, which won't do anything further - in the final line nothing happens with myvar3 's value.
So in the end they have all the same value.
If:
var myvar3 = 5;
var myvar1 = myvar2 = myvar3;
Then they are all = 5
上一篇: 命名与匿名功能:相同?
