基本上,不是閉包如何工作,函數繼承它們的外部作用域。
// this function only inherits the global scope
function writeBody()
{
res.end("<h1> Hooray! </h1>");
}
http.createServer(function(req, res) // a new local varaible res is created here for each callback
{
res.writeHead('Content-Type', 'text/html');
// annonymous function inheris both the global scope
// as well as the scope of the server callback
setTimeout(function(){
// the local variable res is available here too
writeBody()
}, 2000);
}).listen(8000);
爲了讓剛剛工作通過res
對象到函數,因爲它在超時回調的可用。
function writeBody(res)
{
// NOT the same variable res, but it holds the same value
res.end("<h1> Hooray! </h1>");
}
http.createServer(function(req, res)
{
res.writeHead('Content-Type', 'text/html');
setTimeout(function(){
writeBody(res); // just pass res
}, 2000);
}).listen(8000);
但是,你需要注意的事情是這樣的:
for(var i = 0; i < 10; i++) { // only one i gets created here!()
setTimeout(function() {
console.log(i); // this always references the same variable i
}, 1000);
}
這將打印10
十倍,因爲基準是相同的,i
得到增加一路攀升至10
。如果你想要得到不同的數字,你需要爲每個變量創建一個新的變量,通過將setTimeout
包裝成一個匿名的自我函數,你可以通過i
作爲參數傳遞,或者調用其他一些方法來設置timouet並接收i
作爲參數。
// anoynmous function version
for(var i = 0; i < 10; i++) {
(function(e){ // creates a new variable e for each call
setTimeout(function() {
console.log(e);
}, 1000);
})(i); // pass in the value of i
}
// function call version
for(var i = 0; i < 10; i++) {
createTimeoutFunction(i);
}
哦!咄! * facepalm *這有助於減輕痛苦,我只是在腦海中產生了一個轉變時刻。 – MahatmaManic 2010-12-05 08:21:27