Javascript scope undefined

I have a problem with an online jquery site document about the javascript area. There are codes;

(function() {

var baz = 1;

var bim = function() {
    console.log( baz );
};

bar = function() {
    console.log( baz );
};

})();

And says:

console.log( baz ); // baz is not defined outside of the function

what I don't understand is that even if it is bazdetermined why console.log(baz)there is undefined. Because I think the scope is the same. Did I miss something?

+4
source share
3 answers

what i don't understand is that even if the base is defined, why console.log (baz) is undefined

This is undefined because the range is limited (limited) for the IIFE (Immediately Invoked Function Expression) region.

If you bind a variable to a Window object, it will be available worldwide.

Demo

(function() {

  window.baz = 1; // Global
  var pub    = 2; // private

  var bim = function() {
    console.log( baz );
  };

  var bar = function() {
    console.log( pub ); 
  };

  bim(); // 1 //////////
  bar(); // 2 //////////

})(); 


console.log( baz ); // 1 //////////
console.log( pub ); // Ref.Error //
0
source

- IIFE - , .

JS

So baz IIFE.

change this to :

(function() {

 window.baz = 1;     <----

var bim = function() {
    console.log( baz );
};

bar = function() {
    console.log( baz );
};

})();

.

p.s.

jQuery ( bla bla..) $/jQuery . ( , . $ ).

+5

Maybe you are under "strict mode"? Everything is correct in the Chrome console. Call "baz" write 1.

jsfiddle to check jsfiddle.net/Yjq2v/

0
source

All Articles