0

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.

1
  • 2
    None of your examples are really valid... Commented Dec 2, 2011 at 22:38

1 Answer 1

1

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);
});
Sign up to request clarification or add additional context in comments.

1 Comment

That's true, but the OP specifically asked about using an anonymous function, which alert is not.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.