-2
for 루프 내에서 일반 함수 호출 (매개 변수 사용)을 사용하는 것과 IIFE를 사용하는 것 사이에 혼란 스럽습니다.IIFE 대 루프 내의 함수 호출 (매개 변수 포함)
function print_doc_count(i){
var str= "collection" + i.toString();
db.collection(str).count(function(err, res){
if(!err){
console.log("docs in collection: "+str+" = "+res);
}
});
}
예 1 (인생)없이 - -
for(var i=1; i<=10; i++){
print_doc_count(i);
}
예 2 (인생으로) -
for(var i=1; i<=10; i++){
(function print_doc_count(i){
var str= "collection" + i.toString();
db.collection(str).count(function(err, res){
if(!err){
console.log("docs in collection: "+str+" = "+res);
// str needed closure, it contains the value i!
}
});
})(i);
}
는 함수라고하자
제 질문은 위의 Example1과 Example2의 차이점이며 어떤 상황에서 다른 것보다 우선해야합니까? 질문에 대한 의견 @Kevin B에 의해 언급 한 바와 같이
는
흠이다 ? 카운트 콜백 (callback)이 발생하면 그것은 외부에 선언 된 상태로 문제가 발생할 수 있습니다. 두 예제가 for 루프 폐쇄 문제를 해결하려고 시도하는 것처럼 보이지만 두 문법 중 하나만이'str'이 선언 된 방식 때문에 효과적입니다. –
나는 당신을 얻지 않는다. 사과와 오렌지를 비교하려고합니까? – Gogol
@Gogol - console.log는 두 경우 모두 비슷한 결과를 출력하지 않습니까? – vjjj