I have this code
((function(){
var a=2;
var b=3;
var c=b+a;
alert(c);//alert 5
})());
alert(c); //no alert
My question is which ways I can exports c to the global scope? If you can give all the ways. Thank you!
I have this code
((function(){
var a=2;
var b=3;
var c=b+a;
alert(c);//alert 5
})());
alert(c); //no alert
My question is which ways I can exports c to the global scope? If you can give all the ways. Thank you!
Share Improve this question edited Nov 7, 2016 at 8:56 Abulurd 1,0665 gold badges15 silver badges32 bronze badges asked Nov 8, 2012 at 7:11 user1801625user1801625 1,2233 gold badges14 silver badges14 bronze badges4 Answers
Reset to default 4var c = ((function(){
var a=2;
var b=3;
var c=b+a;
alert(c);//alert 5
return c;
})());
alert(c);
There are any number of ways to do this. You could implicitly or explicitly do property assignment on the global as well:
window.c = b+a;
this.c = b+a;
c = b+a;
It's very simple! All global variables in JavaScript are actually a child attribute of the "window" object, so declaring a variable in global scope adds makes that variable an attribute of the window object. From your anonymous function, you can place 'c', or other variables into a global scope simply by doing the following...
window.c=b+a;
alert(c); // Same!
Enjoy :)
var c=0;
((function(){
var a=2;
var b=3;
c=b+a;
alert(c);//alert 5
})());
alert(c); //no alert
(function (window) {
// this is local
var c = 'local';
// export to the global scope
window.c = c || '';
})(window); // Pass in a reference to the global window object
console.log(c) // => 'local'
You can also pass in few other objects and that is not only limited to just one. Here is a really good explanation of how it works