1

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?

asked Jun 14, 2016 at 22:58
1
  • 4
    You can not access this function from the outside unless you make it available to the outside-world from the inside. Commented Jun 14, 2016 at 23:01

3 Answers 3

2

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.

answered Jun 14, 2016 at 23:04
Sign up to request clarification or add additional context in comments.

Comments

1

You can declare a static method. Thus, calling it as MyFunction.FunctionToCall():

var MyFunction = function() {
};
MyFunction.FunctionToCall = function() {
 console.log('MyFunction.FunctionToCall called');
};
$(function() {
 $('div').click(function() {
 MyFunction.FunctionToCall()
 });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<div>Click me</div>

answered Jun 14, 2016 at 23:16

Comments

-1

You are declaring an anonymous function to the variable MyFunction in your code. It will be undefined. You don't want to call anything inside of an anonymous function because anonymous functions are generally immediately called.

Instead, declare your FunctionToCall as a variable outside and then you could define it inside of your anonymous block like this

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

And then you can call FunctionToCall. Though I don't think this is good convention as generally you want to keep functions you use throughout your code on the same scope levels.

answered Jun 14, 2016 at 23:12

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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