简体   繁体   中英

How access to variables within an anonymous function?

I have an anonymous function inside a variable 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(); .

My question is: how I can call functions directly for example GLOBAL.func1() or 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() . And do not confuse with the syntax { func1,func2 }; . That is quite similar to { func1 : func1,func2 : func2 }; I just used the shorthand introduced in 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 ).

You should explicit add those functions in the returned object. In this code you can still continue executing init() as a object initialization.

 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

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();

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