简体   繁体   English

在匿名自执行函数中定义全局函数?

[英]Define global function within anonymous self-executing function?

(function(){

  var someValue = 5;

  function myFunction(input) = {
    return someValue * input;
  };

})();

I have a self-executing function, that contains many things, among them at function that I would like to make global. 我有一个自我执行的功能,其中包含许多内容,其中包括我想使其全局化的功能。 I would typically just declare it in the global scope, but it needs to be able to reference variables that are local only to the self-executing function. 我通常只在全局范围内声明它,但是它需要能够引用仅对自执行函数本地的变量。

What is the best approach to making the function globally-accessible without getting rid of the self-executing function altogether (thus littering the global space with variables)? 什么是使函数可以全局访问而不完全放弃自动执行函数(从而用变量乱扔全局空间)的最佳方法?

You can add the function to the global window object. 您可以将函数添加到全局window对象。

(function(){

  var someValue = 5;

  window.myFunction = function (input) {
    return someValue * input;
  };

})();

After the immediate function executed, you can call myFunction() . 执行立即函数后,可以调用myFunction()

Alternatively, you could do something like this, which has essentially the same result that ntalbs proposed. 或者,您可以执行类似的操作,其结果与ntalbs提出的结果基本相同。

 var myFunction;
 (function(){
     var someValue = 5;
     myFunction = function (input) {
         return someValue * input;
     };
 })();

console.log( myFunction( 4 ), window.myFunction ); // output: 20, function(input){return someValue * input}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在自执行匿名函数中使用undefined - Using undefined in self-executing anonymous function 如何在自执行匿名函数内调用函数? - how to call a function inside a self-executing anonymous function? 匿名自执行js函数内部的全局变量在外部仍然可用? - Global variable inside anonymous self-executing js function still available outside? 自执行匿名功能中的Javascript Google Analytics(分析) - Javascript google analytics in self-executing anonymous function 访问自执行匿名函数中的变量 - Accessing variables inside Self-Executing Anonymous Function 自执行匿名函数中未使用的局部变量警告 - Unused local variable warning in self-executing anonymous function 消除自执行匿名函数中未定义的TypeError - Eliminate undefined TypeError in self-executing anonymous function 如果包装在自动执行匿名 function 中,JavaScript 是否可以“单元测试” - Can JavaScript be “unit testable” if wrapped in self-executing anonymous function 什么是自执行匿名函数或者这段代码在做什么? - what is self-executing anonymous function or what is this code doing? 如何在 Object 中创建自执行匿名 function? - How to create self-executing anonymous function in Object?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM