简体   繁体   English

如何在匿名函数中访问变量?

[英]How access to variables within an anonymous function?

I have an anonymous function inside a variable GLOBAL . 我在变量GLOBAL内有一个匿名函数。

var GLOBAL = function (){

  var func1 = function(){

    console.log("function 1 go!")

  }

  var func2 = function(){

    console.log("function 2 go!")

  }

  return {

    init: function(){

        func1();

    }

  }

}()

In my init function return func1 , calling it so GLOBAL.init(); 在我的init函数中返回func1 ,将其调用为GLOBAL.init(); .

My question is: how I can call functions directly for example GLOBAL.func1() or GLOBAL.func2() . 我的问题是:如何直接调用函数,例如GLOBAL.func1()GLOBAL.func2()

You have to return the function references, 您必须返回函数引用,

var GLOBAL = function (){
  var func1 = function(){
    console.log("function 1 go!");
  }
  var func2 = function(){
    console.log("function 2 go!")
  }
  return { func1,func2 };
}();

Now you can access it like GLOBAL.func1() and GLOBAL.func2() . 现在,您可以像GLOBAL.func1()GLOBAL.func2()一样访问它。 And do not confuse with the syntax { func1,func2 }; 并且不要与语法{ func1,func2 };混淆{ func1,func2 }; . That is quite similar to { func1 : func1,func2 : func2 }; 这与{ func1 : func1,func2 : func2 };非常相似{ func1 : func1,func2 : func2 }; I just used the shorthand introduced in ES6. 我只是使用了ES6中引入的速记。

You can't. 你不能 They are locally scoped variables. 它们是局部范围的变量。 Being inaccessible outside the function is a large part of the point. 在功能之外无法访问是重点。

If you want them to be accessible, then you need to make them so explicitly (as you have done for the anonymous function you assign to init ). 如果希望它们可访问,则需要使它们如此明确(就像您为分配给init的匿名函数所做的那样)。

You should explicit add those functions in the returned object. 您应该在返回的对象中显式添加这些功能。 In this code you can still continue executing init() as a object initialization. 在此代码中,您仍然可以继续执行init()作为对象初始化。

 var GLOBAL = function (){ var func1 = function(){ console.log("function 1 go!") }; var func2 = function(){ console.log("function 2 go!") } return { init: function(){ this.func1(); }, func1, func2 } }(); GLOBAL.func1(); GLOBAL.func2(); 

I hope that helps :D 希望对您有所帮助:D

You can follow modular approach if it can help: 如果可以帮助您,则可以采用模块化方法:

var GLOBAL = {
    func1: function(){
           console.log("function 1 go!")
    },
    func2: function(){
           console.log("function 2 go!")
    }
}

GLOBAL.func1();
GLOBAL.func2();

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

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