简体   繁体   中英

How can I expose local variables defined in anonymous function to the global space?

I have a case where variables are defined inside an self-executing anonymous function. I want to expose them to the global space so I can use foo and bar after the anonymous function returns.

(function () {
    var foo = 123;
    var bar = function () { /* ... */ };
})();

A problem is that I cannot simply do window.foo = 123 or SomeExistingGlobalObject.foo = 123 to expose it because I do not know what comes in inside the anonymous function in advance . The content inside the function is dynamically generated.

I tried returning another self-executing function from that function, but that did not work, either. Is this possible?

Use a revealing module pattern :

var module = (function () {
  var foo = 123;
  var bar = function () {
    console.log('Hallo');
  };
  return { foo: foo, bar: bar }
})();

console.log(module.foo); // 123
module.bar(); // Hallo

DEMO

As an alternate syntax than @Andy you can also go

var module = (function () {
  var fnpublic = {};
  var fubar = 123;

  fnpublic.foo = 123;
  fnpublic.bar = function () {
    console.log('Hallo');
  };

  return fnpublic;
})();

module.foo; // -> 123
module.bar(); // -> "hallo"
module.fubar; // -> undefined

Other elegant way is to do:

(function() {

  var that = this;   // Pass window global scope
  var private_1 = 1; // Create private variable

  // Create method to expose
  var method = function(number) {
    alert(number + private_1);
  };

  // Expose global_obj 
  that.global_obj = {
    alert: method
  };

 }.call(this));


 // In console now you may type
 global_obj.alert(5);

You may have private method as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM