Vijay
Vijay

Reputation: 131

passing an anonymous function to another function in Javascript

I understand you can pass a function as an argument to another function like so

var fn = function(){alert('Hello')}
    function outer(a,fn){
    fn();
    }

How can you pass an anonymous function to another function and have it invoked within the function after taking a parameter from the outer function?

function outer(function(x){alert(x);})
{
var xVar = "foo";
//..would liked to pass xVar to the anaonymous function 
//passed as a param to the function so that "foo" is displayed as message... 
} 

Please note changing the signature of outer would be the last choice.

Upvotes: 0

Views: 311

Answers (1)

Matt Ball
Matt Ball

Reputation: 359826

You're confusing function invocation (calling a function) with function declaration (defining a function). Here's how do what you ask:

// declare the outer function
function outer(func)
{
    var xVar = 'foo';
    func(xVar)
}

// now invoke it
outer(function (x)
{
    alert(x);
});

Upvotes: 1

Related Questions