传递函数作为参数

时间:2012-04-13 17:44:58

标签: javascript

我有两个函数,将其中一个作为参数传递,如:

var a = function(f)
{
  // some code
  f();
};

var b = function()
{
};

a(b); // works great, the function a is executed, then the function b is executed

现在我需要将它扩展到树函数,例如:

var a = function(f)
{
  // some code
  f();
};

var b = function(f)
{
  // some code
  f();
};

var c = function()
{
};

a(b(c)); // but it does not work. b(c) words like a method and get executed right on the instruction.

我该怎么做?

4 个答案:

答案 0 :(得分:3)

传递执行b(c)的包装函数:

a(function() {
    b(c);
});

答案 1 :(得分:2)

听起来你想要使用回调类模式。你可以这样做,而不是简单地传递函数的结果:

var a = function(callback)
{
    // Do Stuff
    callback();
}

var b = function(callback)
{
    // Do Stuff
    callback();
}

var c = function() { }

您的代码最终会如此:

a(function()
{
   b(function()
   {
       c();
   });
});

实际上,在方法完成后传递另一个函数来执行。在上面的场景中,我只提供两个匿名函数作为回调参数。

答案 2 :(得分:1)

function a(f){
  // code
  f()
}
function b(f){
  // code
  a(f())
}
function c(){
  //code
}

b(c);

答案 3 :(得分:1)

一种方法是使用匿名函数:

a(function() { b(c); });