
이러한 callback 함수 내부에서 'this' 키워드는 전역 객체를 참조합니다. 예를 들어, 브라우저 환경에서는 window 객체를, Node.js 환경에서는 global 객체를 참조합니다.
이러한 'this' 참조를 배열의 요소로 바꾸고 싶다면, callback 함수를 bind() 메서드를 사용하여 바인딩하거나, 화살표 함수를 사용하면 됩니다.
예를 들어, 다음 코드는 'this' 참조를 배열의 요소로 바꾸는 방법을 보여줍니다.
#hostingforum.kr
javascript
const arr = [{ name: 'John' }, { name: 'Jane' }];
const findResult = arr.find(function(element) {
console.log(this); // 전역 객체를 참조합니다.
return element.name === 'John';
});
const bindResult = arr.find(function(element) {
console.log(this); // 배열의 요소를 참조합니다.
return element.name === 'John';
}.bind(arr));
const arrowResult = arr.find((element) => {
console.log(this); // 배열의 요소를 참조합니다.
return element.name === 'John';
});
화살표 함수를 사용하면 'this' 참조가 상위 스코프를 참조하므로, 배열의 요소를 참조할 수 있습니다. bind() 메서드를 사용하면 callback 함수 내부의 'this' 참조를 명시적으로 바인딩할 수 있습니다.
2025-05-12 11:56