2016-10-03 4 views
-3

내가 이해하는 한, for 개의 루프는 자바 스크립트에서 별도의 클로저를 만들지 않습니다. 그래서 누군가가 왜 내게 다음 코드에서 dogs 같은 개체에 대한 두 개의 참조가 채워지지 않습니다 설명 할 수 있습니까? 즉 {name: 'lunski', species: 'dog'}이 코드는 왜 클로저처럼 동작합니까?

var animals = [ 
    {name: 'fluffy', species: 'dog'}, 
    {name: 'miauw', species: 'cat'}, 
    {name: 'lunski', species: 'dog'} 
]; 

var dogs = []; 

for(var i = 0, e = animals.length; i<e; i++){ 
    if (animals[i].species === 'dog'){ 
     dogs.push(animals[i]); 
    } 
}; 

나는 dogs[] 모두 배열 요소는 animals[2]에 대한 참조를 보유 것이라고 생각하지만, 사실 배열 dogs은 부드러운 객체와 lunski 객체 모두를 개최한다.

편집 : 그래서 마치 클로저가 만들어지는 것처럼 보입니다. (사실이 아니라고 생각합니다.) 그러나 질문은 여전히 ​​남아 있습니다. dogs[]은 왜 독특한 물체로 가득 찼습니까?

+1

클로저가 여기에 연관되어 있다고 생각하는 이유는 무엇입니까? 이 코드에는 클로저가 없습니다. 이 코드에는 기능이 없습니다. – user2357112

+1

'animals [i]'를 밀면 값을 푸시하는 대신 참조를 생성하지 않습니다. –

+0

함수가 포함되어 있지 않으므로 여기에는 클로저가 포함되어 있지 않습니다. 개 길이는 2입니다. –

답변

2

개념을 혼동하고 있습니다. 이것으로 클로저를 닫으십시오 (완전히 다른 것입니다), 여러분이 물어 본 질문을 보도록하겠습니다.

다음 코드 배열 개는이 같은 오브젝트 {: 'lunski'종 : 이름이 '개'} 작성되지 왜

당신은 두 가지 목적을 추진하고있다

을 (animals[0]animals[2))을 dogs 배열에 추가합니다. animals 개체 (배열은 개체)에 대한 것이 아니라 개별 animals 요소에 포함 된 개체에 대한 참조가됩니다.

이것은 클로저가 아니기 때문에 변수 i은 마지막 값으로 고정되지 않습니다.

UPDATE 내가 마지막으로 의도 한 질문을 이해 생각

- 여기 폐쇄 및 폐쇄하지 않고 익명 함수와 익명 함수는 어레이와 함께 작동하는 방법을 보여주는 대답은 (테스트 this fiddle 참조).

코드/피들은 4 개의 입력을 만듭니다. 첫 번째와 세 번째는 닫힘이없고 두 번째와 네 번째는 닫힘입니다. 입력 내용은 클릭 한 상태이며 (click 청취자가 있음) 콘솔에 각각 animals[i]을 기록합니다. 기록 된 값을 설명하려면 아래 예제의 주석을 참조하십시오.

var animals = [ 
    {name: 'fluffy', species: 'dog'}, 
    {name: 'miauw', species: 'cat'}, 
    {name: 'lunski', species: 'dog'} 
    ]; 

var dogs = []; 
for (var i = 0; i < animals.length; i++) { 
    if (animals[i].species === 'dog') { 
    // the first and third elements created in the loop have no closure 
    // the variable i will be set to 2 because it has reached the end of its loop - it's value was not bound with function 
    // therefore when you click on the input labeled "fluffy (no closure)" or lunski (no closure) they will log "undefined" to the console since animals[2] is undefined. 
     e = document.createElement("input"); 
     e.value = animals[i].name + " (no closure)" ; 
     e.addEventListener('click', function() { 
      console.log(animals[i])} 
     ) 
    document.body.appendChild(e); 


    // the second and fourth elements created in the loop have closure 
    // because the function is enclosed within a function 
    // the variable i will be valid and set to what it is when the funtion runs 
    // Note: The exclamation point causes the outer function to be executed immediately - creating the event listener 
    // therefore when you click on the input labeled "fluffy (closure)" or lunski (closure) 
    // you will see the whole object in the console 
    e = document.createElement("input"); 
    e.value = animals[i].name + " (with closure)" ;; 
    !function(animals, i){ 
     e.addEventListener('click', function() { 
      console.log(animals[i])} 
     ) 
    }(animals, i) 
    document.body.appendChild(e); 
    } 
}; 

이 정보가 도움이되기를 바랍니다. 클로저의 예를 더 보려면 여기를 참조하십시오. SO post

+0

몇 가지 예를 생각해 낼 수 있습니까? – suyesh

+0

@suyesh - 예를 들면? 폐쇄? – mseifert

+0

@suyesh - 클로저에 대해 배우고 싶다면 내 포스트의 하단을 참조하십시오. 링크를 넣었습니다. – mseifert

관련 문제