Domanda

This question has a few answers (sort of) already: Javascript: var = var = function, Multiple Variable Assignments in one row, etc. but I would like to ask a different kind of question about it.

So, this is quite handy to be able to use:

var av = 0, bb;
var cvs = bb = av;
console.log(cvs,bb) // outputs 0 0

My question is, how cross-browser is this? Can I get away with using this everywhere, including IE6 or whatnot, or should I just stick to:

var av = 0, bb;

bb = av; cvs = av;

And if you change one variable at any point in the code, does that mean that the the other variable is changed too, or is there no connection outside of the initial assignment?

Thanks!

È stato utile?

Soluzione

You can rely on this behavior, it is a part of the ECMAScript standard. You can check out the exact details here:
ECMAScript Language Specification (5.1) - Simple Assignment

Altri suggerimenti

To answer your second question:

And if you change one variable at any point in the code, does that mean that the the other variable is changed too, or is there no connection outside of the initial assignment?

That's easy to test:

var av = 0, bb;
var cvs = bb = av;
console.log(av, cvs, bb); // outputs 0 0 0

cvs = 1;
console.log(av, cvs, bb); // outputs 0 1 0

bb = 2;
console.log(av, cvs, bb); // outputs 0 1 2

av = 3;
console.log(av, cvs, bb); // outputs 3 1 2

So there is no connection outside the initial assignment.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top