Javascript从嵌套函数内调用外部函数

Jor*_*hns 4 javascript function function-calls nested-function

拥有我认为应该是一个相对容易的问题来处理成为一个主要的痛苦......我正在尝试做:

a.b("param", function(data)
{
     logger.debug("a.b(" + data.toString() + ")");

     if (data.err == 0)
     {
           // No error, do stuff with data
     }
     else
     {
           // Error :(  Redo the entire thing.
     }
});
Run Code Online (Sandbox Code Playgroud)

我的方法是尝试:

var theWholeThing = function() {return a.b("param", function(data)
{
     logger.debug("a.b(" + data.toString() + ")");

     if (data.err == 0)
     {
           // No error, do stuff with data
     }
     else
     {
           // Error :(  Redo the entire thing.
           theWholeThing();
     }
})};
Run Code Online (Sandbox Code Playgroud)

上面的问题是前者确实有效(除非发生错误时没有处理),后者根本不打印日志消息......就好像“theWholeThing()”调用没有像我认为的那样工作(再次调用整个事情)。

这里一定有什么微妙的错误,有什么提示吗?

谢谢!

Nat*_*all 5

首先,为了直接回答您的问题,听起来您第一次实际上忘记了调用该函数。尝试:

var theWholeThing = function() {return a.b("param", function(data)
{
     logger.debug("a.b(" + data.toString() + ")");

     if (data.err == 0)
     {
           // No error, do stuff with data
     }
     else
     {
           // Error :(  Redo the entire thing.
           theWholeThing();
     }
})};

theWholeThing(); // <--- Get it started.
Run Code Online (Sandbox Code Playgroud)

但是,这可以在命名的 IIFE(立即调用的函数表达式)中更优雅地实现:

// We wrap it in parentheses to make it a function expression rather than
// a function declaration.
(function theWholeThing() {
    a.b("param", function(data)
    {
         logger.debug("a.b(" + data.toString() + ")");

         if (data.err == 0)
         {
               // No error, do stuff with data
         }
         else
         {
               // Error :(  Redo the entire thing.
               theWholeThing();
         }
    });
})(); // <--- Invoke this function immediately.
Run Code Online (Sandbox Code Playgroud)