基本的には、クロージャの仕組みが機能していないので、関数はその外側のスコープを継承します。
// 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);
}
参照が同じであるとi
はすべての方法10
までインクリメントされますので、これは、10
10回を印刷します。異なる番号を持つ場合は、setTimeout
をパラメータとしてi
に渡す匿名のself関数にラップするか、または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