user3334919 user3334919 - 5 months ago 8
jQuery Question

Call a function inside a variable

I'm using this function inside a variable

var MyFunction = (function () {
//......
function FunctionToCall() {
//......
};
//........
}();


I would like to call
FunctionToCall()
with an event handler from outside the variable like this:

$('div').click(FunctionToCall());


Any idea?

Answer

You are probably missing a return statement.
I suppose you intended something like this:

var myFunction = (function() {
  var privateVar = 'Hello';
  
  return function innerFunction() {
    return privateVar;
  };
})();

console.log(myFunction());

Another way is to return an object with the methods that you want to access:

var myThing = (function() {
  var privateVar = 'Hello';

  return {
    innerFunction1: function() {
      return privateVar;
    },
    doSomething: function(newString) {
      privateVar = newString;
    }
  };
})();


myThing.doSomething("Hi!");
console.log(myThing.innerFunction1());

After that you can attach anything you made accessible to your event handler.