2014-05-24 53 views
0

任何人都可以解释为什么以下将无法正常工作? watchLog()中的setTimeout回调将输出未定义。访问变量传递给回调

function initWatchers() { 
    if (config.watchLogs.length >= 1) { 
     config.watchLogs.forEach(function(path) { 
      watchLog(path); 
     }); 
    } 
} 

function watchLog(path) { 
    setTimeout(function(path) { 
     console.log(path) 
    }, 1000); 
} 

回答

3

因为setTimeout,当调用回调函数时,不会传入任何参数到函数中。所以参数path in function (path)没有得到任何值,并且是undefined。此外,它会影响外部范围中的path变量,将其替换(使用undefined)。你实际上需要这个:

function watchLog(path) { 
    setTimeout(function() { 
    // no shadowing arg ^^ 
     console.log(path) 
    }, 1000); 
} 
+0

内部函数的范围是它的父函数的上下文,所以它可以访问变量。 –