How can I export a variable inside an anonymous function to a 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, what methods can I export to the global area? If you can give all the way. Thanks!

+4
source share
4 answers
 var c = ((function(){ var a=2; var b=3; var c=b+a; alert(c);//alert 5 return c; })()); alert(c); 

There are several ways to do this. You could implicitly or explicitly perform property assignments globally:

 window.c = b+a; this.c = b+a; c = b+a; 
+4
source

It is very easy! All global variables in JavaScript are actually a child attribute of the "window" object, so declaring a variable in the addition of a global scope makes this variable an attribute of the window object. From an anonymous function, you can put "c" or other variables in the global scope simply by doing the following ...

 window.c=b+a; alert(c); // Same! 

Enjoy :)

+1
source
 var c=0; ((function(){ var a=2; var b=3; c=b+a; alert(c);//alert 5 })()); alert(c); //no alert 
0
source

 (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 transfer several other objects, and this is not limited to just one. Here is a really good explanation of how this works.

0
source

Source: https://habr.com/ru/post/1444742/


All Articles