简体   繁体   English

如何在JavaScript上运行函数?

[英]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. 我想在JavaScript上运行作为参数发送的函数,例如我创建这个脚本,我希望从这个脚本打印“成功测试”,但脚本将鲸鱼函数打印为文本。 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);

You should return return p1(); 你应该返回return p1();

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

JSFiddle demo JSFiddle演示

the code should be like this: 代码应该是这样的:

test=function (p1) {
        return p1;             
    }

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


console.log(result);

Explanation 说明

To invoke a function passed as a parameter to another function in javascript, you can simple invoke it using the parenthesis as usual. 要调用作为参数传递给javascript中另一个函数的函数,您可以像往常一样使用括号简单地调用它。

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

However, you can also use the function prototype methods Function.prototype.apply() and Function.prototype.call() . 但是,您也可以使用函数原型方法Function.prototype.apply()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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM