2017-09-20 1 views
1

, 나는 최근에이 코드를 작성하고 그것을 작동하지만 난 this.value이 인스턴스를 참조 이해할 수 없습니다이 코드 예제에서 this.value가 무엇을 의미하는지 설명 할 수 있습니까? 나는 자바 스크립트에 새로 온 사람과 여전히 배우고

function displayMatches() { 
const matchArray = findMatches(this.value, cities); //what does this.value refer to? 

const html = matchArray.map(place => { 

const regex = new RegExp(this.value,'gi'); 

const cityName = place.city.replace(regex,`<span class="hl">${this.value} 
</span>`); 

const stateName = place.state.replace(regex,`<span class="hl">${this.value} 
</span>`); 

return ` 
<li> 
    <span class="name">${place.city}, ${stateName}</span> 
    <span class="population">${numberWithCommas(place.population)}</span> 
</li> 
`; 
}).join (''); 
suggestions.innerHtml = html; 
} 

는 생각이에 언급했다 wordsToMatch는 다음과 같습니다.

const cities = []; 
fetch(endpoint) 
    .then(blob => blob.json()) 
    .then(data => cities.push(...data)); 

function findMatches(wordToMatch) { 
    return cities.filter(place => { 
    const regex = new RegExp(wordToMatch, 'gi'); 
    return place.city.match(regex) || place.state.match(regex) 
    }); 
} 

function displayMatches() { 
    const matchArray = findMatches(this.value, cities); 
    const html = matchArray.map(place => { 
    const regex = new RegExp(this.value, 'gi'); 
    const cityName = place.city.replace(regex, `<span class="hl">${this.value}</span>`); 
    const stateName = place.state.replace(regex, `<span class="hl">${this.value}</span>`); 
return ` 
    <li> 
    <span class="name">${cityName}, ${stateName}</span> 
    <span class="population">${numberWithCommas(place.population)}</span> 
    </li> 
`; 
    }).join(''); 
    suggestions.innerHTML = html; 
} 

const searchInput = document.querySelector('.search'); 
const suggestions = document.querySelector('.suggestions'); 

searchInput.addEventListener('change', displayMatches); 
searchInput.addEventListener('keyup', displayMatches); 

아무에게도 설명해 줄 수 있습니까? 정말 고맙겠 어! 나는이.() 방법 전체가 여전히 매우 혼란 스럽다는 것을 안다.

+3

이벤트 핸들러로 'displayMatches'가 사용 되었기 때문에 브라우저가 함수를 호출 할 때'this' 값은 이벤트와 관련된 DOM 요소에 대한 참조가됩니다. – Pointy

+1

... 그리고'input' 엘리먼트는'value' 속성을 가지고 있습니다. 그래서'this.value'는 이벤트가 걸린 입력의'value' 속성에 접근합니다. –

+0

docs : https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#The_value_of_this_within_the_handler –

답변

0

일부 이벤트를 바인딩 할 때 어떤 이벤트를 바인딩 할 때 은 해당 이벤트가 처리기 메서드에 보내는 정보입니다. 코드의이 라인에서 :

searchInput.addEventListener('change', displayMatches); 

는이가 searchInput 요소이며, 다음 displayMatches에서() 문맥 를 요소 searchInput을 듣고있다.

그런 식으로 this.value는 searchInput.value입니다.

갖고 계십니까?

+0

저를 위해이 문제를 해결해 주셔서 감사합니다. 나는 그것을 지금 이해한다. – KatherineMichelle

+0

안녕하세요. @KatherineMichelle –

0

함수 내부에서이 값은 함수가 호출되는 방식에 따라 다릅니다. 함수를 호출 한 DOM 요소를 참조합니다.
은의이 당신의 자바 스크립트입니다 가정 해 봅시다 :

function alertMessage() { 
    alert(this.value); 
} 

그리고 이것은 당신의 HTML입니다 :

<input type="text" onmousehover="alertMessage()" value="Test"> 

마우스 자바 스크립트 "테스트"를 알려줍니다 입력 요소를 가져됩니다 입력 값 때문에 이 함수를 호출 한 함수는 Test입니다.

관련 문제