2

I want to run function sent as parameter on JavaScript, for example I create this script, I want from this script to print "successful test" but the script print the whale function as text. Thus, how can I run a function sent as parameter to the function?

test=function (p1) {
        return p1;             
    }
var result=test(function(){
    return "successful test";
});
console.log(result);
3
  • you want to return p1(); Commented Oct 10, 2015 at 2:15
  • I want to return the result of p1 Commented Oct 10, 2015 at 2:15
  • yes that is correct - that is what you need to change your code to return p1() rather than return p1 Commented Oct 10, 2015 at 2:16

3 Answers 3

4

You should return return p1();

var test=function (p1) {
        return p1();             
    }
var result=test(function(){
    return "successful test";
});
console.log(result);

JSFiddle demo

Sign up to request clarification or add additional context in comments.

Comments

2

the code should be like this:

test=function (p1) {
        return p1;             
    }

var result=test(function(){
    return "successful test";
}());


console.log(result);

1 Comment

I like this because it doesn't force p1 to be a function. It's self calling so it resolves to a standard variable.
1

Explanation

To invoke a function passed as a parameter to another function in javascript, you can simple invoke it using the parenthesis as usual.

function myFunction(callback) {
   return callback();
}

However, you can also use the function prototype methods Function.prototype.apply() and Function.prototype.call().

Example

<!DOCTYPE html>
<html>

<head>

  <meta charset="UTF-8">

</head>

<body>

  <script>
    function myFunction() {
      return 'success <br />';
    }

    function simpleInvocation(fn) {
      document.write('<h1>simple</h1>');
      return fn();
    }

    function callInvocation(fn) {
      document.write('<h1>call</h1>');
      return fn.call(this);
    }

    function applyInvocation(fn) {
      document.write('<h1>apply</h1>');
      return fn.apply(this);
    }

    document.write(simpleInvocation(myFunction));

    document.write(callInvocation(myFunction));

    document.write(applyInvocation(myFunction));
  </script>

</body>

</html>

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.