【问题标题】:Javascript calling outer function from within nested functionJavascript从嵌套函数中调用外部函数
【发布时间】:2012-11-20 14:09:26
【问题描述】:

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

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.
     }
});

我的方法是尝试:

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()”调用没有像我一样工作认为它应该(再次调用整个事情)。

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

谢谢!

【问题讨论】:

    标签: javascript function function-calls nested-function


    【解决方案1】:

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

    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.
    

    但是,这可以在命名的 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.
    

    【讨论】:

    • 这解决了问题,谢谢! (没有意识到问题是我没有调用函数开始......大声笑)会尽快接受答案所以让我(1分钟)
    【解决方案2】:

    如果把方法分开,用变量来表示,事情就清楚了。您只需要将 a.b 和匿名函数视为方法引用。我认为这个代码示例可以提供帮助:

    var theWholeThing = a.b, //this is a reference of b method
        par = "param",
        callback = function(data){
         logger.debug("a.b(" + data.toString() + ")");
    
         if (data.err == 0)
         {
               console.log("no error");    
         }
         else
         {
               console.log("Error");
               // theWholeThing reference can be accessed here and you can pass your parameters along with the callback function using variable name 
               theWholeThing("param", callback); 
         }
    }; //declare the callback function and store it in a variable
    
    theWholeThing("param", callback); //invoke it
    

    【讨论】: