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