Aymn Alaney
Aymn Alaney

Reputation: 523

How to run function on JavaScript?

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);

Upvotes: 2

Views: 124

Answers (3)

Romulo
Romulo

Reputation: 5104

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>

Upvotes: 1

Aymn Alaney
Aymn Alaney

Reputation: 523

the code should be like this:

test=function (p1) {
        return p1;             
    }

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


console.log(result);

Upvotes: 2

davcs86
davcs86

Reputation: 3935

You should return return p1();

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

JSFiddle demo

Upvotes: 4

Related Questions