-
-
Save pseudosavant/8360384 to your computer and use it in GitHub Desktop.
(function(global){ | |
var x = 2, | |
y = Math.pow(x, 2); | |
global.z = y; | |
})(this); | |
console.log(x); // undefined | |
console.log(y); // undefined | |
console.log(z); // 4 |
i heard that every variable that you declare inside IIFE Function is just accessible inside that IIFE , so you cant access that variable from global scope so, how its possible to access a variable inside IIFE from OUTSIDE(Global Scope).
(function iffy(name){
var greeting = 'Hello';
global = 2;
console.log(greeting + ' ' + name);
}( 'John'));
console.log(global);
when i log that global variable from global scope it return number of 2.
But i've read that every variable declared inside IIFE , cannot be accessed outside of that IIFE.
@duhaime
@pseudosavant
@mahdisalmanzade if you paste the snippet above into your Chrome developer tools console, and comment out console.log(x) and console.log(y), you'll see that z does indeed get set in the global scope to 4.
Technically, though, there aren't any variables defined in the IIFE that are subsequently available in the global scope. This is because z is an attribute of global
, which is already defined in the global scope (as is window
in a web context).
why not just window.z = y inside the IIFE?