开发者

How to declare global variables using JS

How to declare a global variable using JavaScript, whose life remain through o开发者_开发问答ut the HTML code? Can we access the variable that we had declared in one script in another script?


"Don't do this" is the simple answer. Clogging the global scope is generally a bad thing, especially if you have to ask how (which usually means that you're asking because you think it's the easy solution, but it's almost certainly not the right one). What exactly are you trying to do?

If you really want to, either:

  • declare it outside of any function
  • don't use the var keyword
  • use window.variable = value


Declare a variable outside any function. It will be accessible in other scripts.


Global variables are declared by using either the var keyword outside of the scope of a function, by assigning a variable without using var, or by directly assigning a property of the window object.

<script>
var global1 = 'foo';
global2 = 'bar';
window.global3 = 'baz';
function f() {
    var not_global;
}
</script>


Declare a variable in a script tag before your other scripts.

<script type="text/javascript">
   var global = "hello world";
</script>


Declare your variable in a <script> tag, but make sure to place it within your <body> tag, or the browser may not execute it!

Alternatively you may use a cookie.


Any variable that is defined outside a function or a class is global variable in Javascript.

For example:

<script>
    var itsAGlobalVariable;
    function someMethod() {
        var itsALocalVariable;
    }
</script>


You mean something like this:

   var Foo = {
       Bar: Value
   }

Then you can access to this like that:

Foo.Bar

You can also set values:

Foo.Bar = "fancy value"
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜