简体   繁体   中英

How can I export a variable inside of an anonymous function to the global scope in JavaScript?

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!

var 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM