2013-06-03 21 views

回答

6

它們沒有全局範圍。

Route

該路由爲每個路由採用一個處理函數。該路線通過reqres對象。

app.get('/my-route', myHandler); 

處理器

你的處理程序會收到這些對象,並使用它們。

exports.myHandler = function(req, res) { 
    res.send("Hello world"); 
); 

瓶蓋

當您進行數據庫調用(或任何其他IO綁定調用)傳遞給它的回調。 reqres對象作爲閉包存在於該回調中。

exports.myHandler = function(req, res) { 
    var weekday = req.query.weekday || "today"; 
    db.getWeather(weekday, function(err, result) { 
    // `res` here is a closure 
    if(err) { res.send(500,"Server Error"); return; } 
    res.send(result); 
    }); 
}; 

更多有關閉:How do JavaScript closures work?

相關問題