开发者

What is the outcome of: var myvar1 = myvar2 = myvar3?

开发者 https://www.devze.com 2023-04-06 13:21 出处:网络
I have seen in some nodejs scripts variables/objects being used like this: 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开发者_JS百科 what does it mean?


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.


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;


If:

var myvar3 = 5;

var myvar1 = myvar2 = myvar3;

Then they are all = 5


myvar1 and myvar2 both get the name of myvar3. the first expression to evaluate is myvar2 = myvar3. This assigns myvar3 to myvar2. The result of this operation is the assigned value , and this is then assigned to myvar1.


This will assign the variables myvar1 and myvar2 to the value of myvar3. Why they do this is unknown to me, but my best guess is they want the two vars to be the same value of myvar3.


as already explained, the statement results in all variables having the value myvar3.

I like to add: using statements like that you have to beware of scope, demonstrated by:

function foo(){
  var c = 1;
  var a = b = c;
  console.log(a,b,c); //=> 1 1 1
  c = 2;
  console.log(a,b,c); //=> 1 1 2
}
console.log(b); //=> 1! [b] is now a variable in the global scope 

And of assigning non primitive values (so, references to objects)

function foo(){
  var c = {};
  var a = b = c;
  c.bar = 2;
  console.log(a.bar,b.bar,c.bar); 
       //=> 1 1 1 (a, b and c point to the same object)
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号