简体   繁体   English

如何将匿名函数内的变量导出到JavaScript中的全局作用域?

[英]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.

相关问题 我可以在函数内定义一个javascript变量(不是全局变量),并且该变量在其作用域内是可见的吗? - Can I define a javascript variable (not global) inside a function and this variable be visible ouside his scope? Javascript全局变量仅在匿名函数内更新 - Javascript Global variable only update inside anonymous function 如何访问 JavaScript 匿名函数中的变量 - How to access variable inside JavaScript anonymous function 如何在JavaScript中从内部调用匿名函数? - How can I call an anonymous function from inside itself in JavaScript? 如何在该匿名javascript中调用该函数? (TinyMce示例) - How can i call that function inside that anonymous javascript? (TinyMce example) Javascript:虽然在全局范围内声明了变量,但在函数内部仍未定义 - Javascript: While the variable is declared in global scope, it remains undefined inside the function 如何在匿名 function 中引用和分配全局变量? - How to refer and assign to a global variable inside an anonymous function? 如何在javascript函数内部定义全局变量并在其外部访问它? - How can I define a global variable inside javascript function and access it outside it? javascript匿名函数:如何在全局命名空间中公开此变量 - javascript anonymous function : how is this variable exposed in global namespace 全局变量在匿名函数中不起作用 - global variable not working inside anonymous function
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM