ForEach에서 this 사용해보자
잘못된 예시
- 해당 함수 상위에 있는 전역객체 window 출력
var arrTest = {
names: ["aaa", "bbb", "ccc"],
thisTestFunc: function () {
console.log(this); //names 배열 출력
arrTest.names.forEach(function () {
console.log(this); //window 객체 출력
});
},
};
arrTest.thisTestFunc();
잘된 예시 1.
forEach( function( … ){ … }, this )
var arrTest = {
names: ["aaa", "bbb", "ccc"],
thisTestFunc: function () {
console.log(this); //names 배열 출력
arrTest.names.forEach(function () {
console.log(this);
}, this);
},
};
arrTest.thisTestFunc();
잘된 예시 2. Arrow Function 사용
- 어떻게 가능하냐면, Arrow Function을 둘러 싼 lexically environment 즉, thisTestFunc 함수의 this 값을 가져옴
- thisTestFunc 함수의 this = var arrTest 객체 값과 동일
var arrTest = {
names: ["aaa", "bbb", "ccc"],
thisTestFunc: function () {
console.log(this); //names 배열 출력
arrTest.names.forEach(() => { console.log(this); });
},
};
arrTest.thisTestFunc();
반응형
'개발 > 자바스크립트 및 프론트' 카테고리의 다른 글
자바스크립트 ) Modal 영역 밖 클릭 여부 확인 (0) | 2023.06.20 |
---|---|
제이쿼리) parent 지옥에서 탈출하기, closest 사용하기 (0) | 2023.04.08 |
(HTML) 테이블 세로 중앙 정렬 (0) | 2022.09.06 |
자바스크립트 ) 화면 -> 화면으로 데이터 전송하기 (0) | 2022.08.31 |
자바스크립트) 무한스크롤 - 스크롤 최하단 Check (0) | 2022.08.29 |
댓글