简体   繁体   English

在匿名闭包函数中定义全局函数

[英]Define global function inside anonymous closure function

Is there any way to define within closure a global function? 有什么方法可以在闭包内定义全局函数吗? I would like to define one global function so I can call it with onclick event. 我想定义一个全局函数,以便可以通过onclick事件调用它。

(function(){

 var private = 'private msg';

 function myprivate() {
   alert(private)
 }

 function wanttobeglobal() {
   alert(global) 
 }

})();

Is there any way? 有什么办法吗?

Assign the function to window : 将函数分配给window

(function(){

 var private = 'private msg';

 function myprivate() {
   alert(private)
 }

 window.wanttobeglobal = function wanttobeglobal() {
   alert(global) 
 }

})();

Very bad practice, but the only way short of declaring the variable outside the initial closure is to implicitly create a global variable. 这是非常不好的做法,但是在初始闭包之外声明变量的唯一方法是隐式创建全局变量。

wanttobeglobal = function() {
  alert(global);
};

The better way, if you can modify code outside of the closure, is with var : 如果可以在闭包之外修改代码,更好的方法是使用var

var wanttobeglobal;

(function() {
  // ...
  wanttobeglobal = function() {
    alert(global);
  };
})();

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

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