2014-05-24 55 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

內部函數的範圍是它的父函數的上下文,所以它可以訪問變量。 –