admin管理员组

文章数量:1279177

In a JavaScript environment can I declare a variable before a function to make the variable reachable on a global level. For instance:

var a;
function something(){
  a = Math.random()
}

Will this make "a" a global variable?

or is using...

var a = function(){
  var b = Math.random();
  return b;
}
document.write(a())

Really the only way to do it?

Is there a way to make "b" global other than calling the function "a()"?

In a JavaScript environment can I declare a variable before a function to make the variable reachable on a global level. For instance:

var a;
function something(){
  a = Math.random()
}

Will this make "a" a global variable?

or is using...

var a = function(){
  var b = Math.random();
  return b;
}
document.write(a())

Really the only way to do it?

Is there a way to make "b" global other than calling the function "a()"?

Share Improve this question edited Jan 14, 2013 at 4:29 steveax 17.7k6 gold badges46 silver badges59 bronze badges asked Jan 14, 2013 at 4:23 user1690995user1690995
Add a ment  | 

3 Answers 3

Reset to default 10

There are basically 3 ways to declare a global variable:

  1. Declaring it in the global scope, outside of any function scope.
  2. Explicitly assigning it as a property of the window object: window.a = 'foo'.
  3. Not declaring it at all (not remended). If you omit the var keyword when you first use the variable, it'll be declared globally no matter where in your code that happens.

Note #1: When in strict mode, you'll get an error if you don't declare your variable (as in #3 above).

Note #2: Using the window object to assign a global variable (as in #2 above) works fine in a browser environment, but might not work in other implementations (such as nodejs), since the global scope there is not a window object. If you're using a different environment and want to explicitly assign your global variables, you'll have to be aware of what the global object is called.

Will this make "a" a global variable?

A var declaration makes the variable local to the enclosing scope, which is usually a function one's. If you are executing your code in global scope, then a will be a global variable. You could as well just omit the var, then your variable would be implicitly global (though explicit declaration is better to show your intention).

Is there a way to make "b" global other than calling the function "a()"?

Your b variable is always local to the function a and will never leave it, unless you remove the var.

Before you think of making a variable global scope, you should consider JavaScript global namespace pollution. The more global variables you declare, the more it is likely that you application will get into conflict with another application's namespace and break. As such, it is highly important minimize the number of global variables.

本文标签: javascriptDeclaring Empty Variables to make them globalStack Overflow