, 나는 최근에이 코드를 작성하고 그것을 작동하지만 난 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);
아무에게도 설명해 줄 수 있습니까? 정말 고맙겠 어! 나는이.() 방법 전체가 여전히 매우 혼란 스럽다는 것을 안다.
이벤트 핸들러로 'displayMatches'가 사용 되었기 때문에 브라우저가 함수를 호출 할 때'this' 값은 이벤트와 관련된 DOM 요소에 대한 참조가됩니다. – Pointy
... 그리고'input' 엘리먼트는'value' 속성을 가지고 있습니다. 그래서'this.value'는 이벤트가 걸린 입력의'value' 속성에 접근합니다. –
docs : https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#The_value_of_this_within_the_handler –