[英]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.
JavaScript中的所有全局变量实际上都是“窗口”对象的子属性,因此在全局范围添加中声明变量会使该变量成为窗口对象的属性。 From your anonymous function, you can place 'c', or other variables into a global scope simply by doing the following...
从您的匿名函数中,您可以将“c”或其他变量放入全局范围,只需执行以下操作即可...
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
这是一个很好的解释它是如何工作的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.