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?
-
4You can not access this function from the outside unless you make it available to the outside-world from the inside.tkausl– tkausl2016年06月14日 23:01:13 +00:00Commented Jun 14, 2016 at 23:01
3 Answers 3
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.
Comments
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>
Comments
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.