CMedina
CMedina

Reputation: 4222

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

Upvotes: 0

Views: 80

Answers (4)

Mohammad Usman
Mohammad Usman

Reputation: 39322

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

Upvotes: 0

Fabricio
Fabricio

Reputation: 3297

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

Upvotes: 1

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67207

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.

Upvotes: 3

Quentin
Quentin

Reputation: 943510

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).

Upvotes: 2

Related Questions