Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this questionWhat's best...
create variables like this:
var one = 1;
var two = 2;
var three = 3;
or like this:
var myStuff = {}
myStuff.one = 1;
myStuff.two = 2;
myStuff.three = 3;
I've seen both ways and don't understand what the main difference is. Can anyone clarify for me please.
With the first...
- it adds 3 names to the variable environment
- the variables can not be directly accessed outside its variable environment
With the second...
- it creates an object, and assigns it to a single name in the environment
- the object itself can be passed outside the enclosing environment
- updates to the object can be observed by whatever code is referencing the object
The main difference is that the first method gives you three separate variables, named "one", "two", and "three". They are not related to each other, not connected in any way. The second method puts all the variables into an Array called "myStuff".
Keeping them separate, as in the first method, is often what you want for simple cases. If you need to have them bound together for some reason, for example to pass the set of variables to a function, then the array method would be better.
var one = 1;
var two = 2;
var three = 3;
Creates three variables with three identifiers
var myStuff = {}
myStuff.one = 1;
myStuff.two = 2;
myStuff.three = 3;
creates a single variable (myStuff) containing three members. The advantage is namespace separation, and the ability to pass/copy/delete the whole variable as one.
精彩评论