Function areas and global variables

var foo = '1',
    bar = '2';

console.log(foo, bar, window.foo); //1, 2, undefined

(function(foo){
    console.log(foo, bar); //2, 2
})(bar);

I have two trivial questions regarding the code above:

  • Why window.fooundefined? Are all global variables bound to the window object?

  • Why foo ===2 inside closure? I know that convey the original baralias foo, which is equal to 2, but outside the scope foostill 1. And, as far as I know, the source foocan be accessed from within the closing device. Is "new foo" a priority because it is passed as an argument to IIFE?

http://jsfiddle.net/GbeDX/

+5
source share
4 answers

window.foo undefined? "" ?

, window, . load (. , "onLoad" ). : http://jsfiddle.net/GbeDX/1/

foo === 2 ? [...] , , foo .

, . foo foo. , window.foo.

+9
  • . , , Firebug, jsFiddle ..,

  • 2 , foo. , , foo .

+1
  • window.foo === '1', .
  • foo === '2' , foo . foo, .
+1
  • Yes. You probably see the variable fooas undefinedbecause you are using a script in a debugging environment like firebug or jsfiddle (linked by fooobar.com/questions/373921 / ... )
  • No. The foooption to overwrite the variable foo. But this is still a global variable, so you can use it as window.foo.
0
source

All Articles