user701254
user701254

Reputation: 3943

Passing a function as an argument in a separate function

I have a function that i want to pass as a parameter

function myFun(){

}

function myFunParam(myFun){

}

is above code correct ? How do I call the function myFun within myFunParam ?

Upvotes: 1

Views: 94

Answers (6)

Nikhil D
Nikhil D

Reputation: 2509

function outerFunction(innerFunction) {
    innerFunction(); // call inner function
}

Upvotes: 0

ilyes kooli
ilyes kooli

Reputation: 12043

function myFun(){
}

function myFunParam(myFun){
    if ($.isFunction(myFun)){         
        //Added example of passing arguments to myFun
        myFun.apply(this, ['arg1', 'arg2', 'arg3']);
    }
}

You can also pass anonymous functions,

myFunParam(function(){
    alert('anonymous function');
});

Upvotes: 1

Sarfraz
Sarfraz

Reputation: 382696

function myFun(){
   alert('test');
}

function myFunParam(myFun){
   if (typeof myFun === "function")
      myFun(); // alerts "test"
}

If your function, needs an argument, you would do:

function myFun(myarg){
   alert(myarg);
}

function myFunParam(myFun){
   if (typeof myFun === "function")
      myFun('foo'); // alerts "foo"
}

Or you can also pass any number of arguments using arguments object (actually an array-like object).

Upvotes: 3

kiranvj
kiranvj

Reputation: 34117

OR you can do like this also

var newFunction = function() {
alert("I am in newFunction");
}


function calleFunction(func) {
func();
}

calleFunction(newFunction);

Upvotes: 0

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167182

Your code is right. You need to call this way:

function myFun(){
}

function myFunParam(myFun){
    // Other Statements
    myFun();
}

Hope it helps! :)

Upvotes: 0

Philippe Leybaert
Philippe Leybaert

Reputation: 171774

It's correct, but I would certainly rename the parameter to avoid confusion between the global myFun and the parameter:

function myFunParam(func) {
    func(); // call function
}

Upvotes: 1

Related Questions