2015-10-10 35 views
2

我想在JavaScript上运行函数作为参数发送,例如我创建了这个脚本,我希望从这个脚本打印“成功的测试”,但脚本将文本打印为鲸鱼功能。 因此,我如何运行一个函数作为参数发送给函数?如何在JavaScript上运行函数?

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

到'回报P1();' –

+0

我想返回的结果P1 –

+0

是的,这是正确的 - 这是你需要改变你的什么代码到'返回p1()'而不是'返回p1' –

回答

4

您应该返回return p1();

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

JSFiddle demo

2

的代码应该是这样的:

test=function (p1) { 
     return p1;    
    } 

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


console.log(result); 
+0

我喜欢这个,因为它不强制'p1'是一个函数。这是自我调用,所以它解析为一个标准变量。 – aviemet

1

说明

要调用A F作为参数传递给javascript中的另一个函数,您可以像往常一样简单地使用括号来调用它。

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

但是,您也可以使用函数原型方法Function.prototype.apply()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>

你想