0

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

2
  • 1
    You can't unless you pass the reference via the return Commented Apr 14, 2016 at 14:43
  • Why do you want to do this? Commented Apr 14, 2016 at 14:43

4 Answers 4

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

What kinda pattern is this?
@Roy Singleton pattern.
2

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

Comments

1

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.