Reputation: 523
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
Reputation: 5104
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()
.
<!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
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
Reputation: 3935
You should return return p1();
var test=function (p1) {
return p1();
}
var result=test(function(){
return "successful test";
});
console.log(result);
Upvotes: 4