最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin3浏览0评论

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!

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!

Share Improve this question edited Nov 7, 2016 at 8:56 Abulurd 1,0665 gold badges15 silver badges32 bronze badges asked Nov 8, 2012 at 7:11 user1801625user1801625 1,2233 gold badges14 silver badges14 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 4
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

发布评论

评论列表(0)

  1. 暂无评论