기본적으로 클로저가 작동하지 않는 함수는 외부 함수 범위를 상속받습니다.
// 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);
은 그러나이 같은 것들을 조심해야합니다 참조가 동일하며 i
이 10
모든 방법까지 증가됩니다 때문에
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
열 번 인쇄됩니다. 서로 다른 숫자를 가지려면 각각의 변수를 새로 만들 필요가 있습니다. 에 전달하는 익명 자체 함수에
setTimeout
을 래핑하거나 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);
}
오! 이런! * 페이스 팔먼 * 그게 도움이되는 톤, 난 그냥 내 머리에 shift - ey 순간을했다. – MahatmaManic