2012-07-19 25 views
0

如何在JavaScript中将函数作为参数传递。在JavaScript中传递函数作为参数

在下面的代码,如果我叫whatMustHappen (TWO(),ONE())我想他们落入x的序列,并在whatMustHappen功能y英寸

现在它会在参数中看到它时触发。

var ONE = function() { 
    alert("ONE"); 
} 
var TWO = function() { 
    alert("TWO"); 
} 
var THREE = function() { 
    alert("THREE"); 
} 
var whatMustHappen = function(x, y) { 
    y; 
    x; 
} 
whatMustHappen(TWO(), null); 
whatMustHappen(TWO(), ONE()); 

回答

2
var whatMustHappen = function(x, y) { 
     if (y) y(); 
     if (x) x(); 
    } 
whatMustHappen(TWO, null); 
whatMustHappen(TWO, ONE); 
+0

这将导致错误,没有什么会真的发生 – Esailija 2012-07-19 10:23:30

+0

哪个错误,为什么?由于null? OP应该照顾这一点。无论如何,更新我的答案。 – Dev 2012-07-19 10:24:17

2

()调用一个功能并返回其结果。要通过一个函数,你只需通过它像任何其他变量:

whatMustHappen(TWO, ONE); 

whatMustHappen功能,你就可以打电话给他们:

var whatMustHappen = function(x, y) { 
     if(y) y(); 
     if(x) x(); 
    } 
0

如果你想传递一个函数,不叫它(与(args))。

function foo() { 
    alert("foo"); 
} 

function bar (arg) { 
    alert("Function passed: " + arg); 
    arg(); 
} 

bar(foo); 
相关问题