coding style - javascript global variable scope - Stack Overflow

admin2025-04-04  0

So I hear that variable in js that initialized without a "var" will be global. so:

$(document).ready(function(){
      function foo(){
         //since i'm not using "var", will this function bee global?
      }

      var bar = function(){
         //is this the better way to declare the function?
      }
})

If it is global, why I can't access it in the console. If it's not global, and it's scope is in the function, will omitting "var" cost some performances? Thanks.

So I hear that variable in js that initialized without a "var" will be global. so:

$(document).ready(function(){
      function foo(){
         //since i'm not using "var", will this function bee global?
      }

      var bar = function(){
         //is this the better way to declare the function?
      }
})

If it is global, why I can't access it in the console. If it's not global, and it's scope is in the function, will omitting "var" cost some performances? Thanks.

Share Improve this question asked Jan 24, 2012 at 18:53 randomorrandomor 5,6755 gold badges49 silver badges70 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 13

Only variables declared without var bee global, this does not apply to functions.

You can, however, declare foo like so:

foo = function() {}

and it should be global.

Omitting var is generally not remended for these reasons (off the top of head):

  • Variable resolution starts at the most local and goes toward looking in the global namespace, making it slower. Much slower in certain browsers.
  • You tend to eventually have naming conflicts by polluting the global namespace. One of the worst offenders would be, say, for(i = 0; i < arr.length; i++) (note the lack of var)

You might want to declare functions using var due to a language feature called hoisting

BTW, if you do choose to declare functions with var, I remend you do so this way:

var foo = function foo() {}

because it gives the function a "name" instead of being treated as an anonymous function, which will help with debugging. Most people do not do this and declare using function, I believe.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1743749495a217401.html

最新回复(0)