user1801625 user1801625 - 1 month ago 20
Javascript Question

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!

Answer
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;