开发者

best way to create javascript variables [closed]

开发者 https://www.devze.com 2023-04-13 04:54 出处:网络
开发者_如何学运维Closed. This question is opinion-based. It is not currently accepting answers.
开发者_如何学运维Closed. This question is opinion-based. It is not currently accepting answers.

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 question

What'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.

0

精彩评论

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