
this 키워드를 사용할 때는 콜백 함수 내에서 전역 객체인 window 또는 global 객체를 참조하도록 설정해야 합니다.
콜백 함수를 전역 객체의 메서드로 설정할 수 있습니다.
#hostingforum.kr
javascript
const arr = [1, 2, 3, 4, 5];
const result = arr.find(function(element) {
console.log(this); // 전역 객체 window 또는 global
return element > 3;
});
console.log(result); // 4
또는 bind 메서드를 사용하여 콜백 함수 내의 this 키워드를 설정할 수 있습니다.
#hostingforum.kr
javascript
const arr = [1, 2, 3, 4, 5];
const result = arr.find(function(element) {
console.log(this); // 전역 객체 window 또는 global
return element > 3;
}.bind(this)); // this를 전역 객체 window 또는 global로 설정
console.log(result); // 4
또는 화살표 함수를 사용하여 this 키워드를 생략할 수 있습니다. 화살표 함수 내의 this 키워드는 상위 스코프의 this 키워드를 참조합니다.
#hostingforum.kr
javascript
const arr = [1, 2, 3, 4, 5];
const result = arr.find((element) => {
console.log(this); // 상위 스코프의 this 키워드를 참조
return element > 3;
});
console.log(result); // 4
콜백 함수 내의 this 키워드를 설정하는 방법은 여러 가지가 있습니다. 위의 예제에서 설명한 것과 같이 bind 메서드를 사용하거나 화살표 함수를 사용하는 것이 일반적인 방법입니다.
2025-04-08 03:54