0

How to create a function that accepts the parameter as a function?

I have this function and I want to call it with parameter of a function also:

function ShowDialog(OnSubmit) 
{
    var _result = OnSubmit();

    alert(_result);
}

This is what I want to call:

ShowDialog(
              {
                  OnSubmit: function () {
                      return "Hello World";
                  }
              }
          );

this will alert "Hello World in browser"
2
  • 1
    You're passing an object with a property but expecting a function… Commented Oct 24, 2013 at 9:37
  • What is the requirement behind this??? Commented Oct 24, 2013 at 9:49

3 Answers 3

4

Call:

ShowDialog(function(){
   return "Hello World";
});

Then your function can remain as:

function ShowDialog(OnSubmit) 
{
    var _result = OnSubmit();

    alert(_result);
}
Sign up to request clarification or add additional context in comments.

Comments

1

JavaScript has first-class functions, so you can just pass the function reference directly, you do not need an object:

function showDialog(callback) {
    var result = callback();
    alert(result);
}

function bye() { return "bye!" };

showDialog(function() { return "Hello!" });
showDialog(bye);

var greetings = { ciao: function() { return "Ciao!" } };

showDialog(greetings.ciao);

Of course you can also pass the full object, in that case you need to modify the function as follow:

function showDialog(options) {
    var result = options.onSubmit();
    alert(result);
}

And then:

showDialog({
    onSubmit: function() { return "Hello!" }
});

showDialog({
    onSubmit: bye
});

You could also implement a function that accepts both object and callback:

function showDialog(options) {
    var result = typeof options === 'function' ? options() : options.onSubmit();
    alert(result);
}

showDialog({
    onSubmit: bye
});

showDialog(bye);

Hope it helps.

Comments

1

Try this instead:

function ShowDialog(param) 
{
    var _result = param.OnSubmit();
    alert(_result);
}

ShowDialog({
    OnSubmit: function () {
         return "Hello World";
    }
});

Comments

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.