본문 바로가기
개발/자바스크립트 및 프론트

자바스크립트 ) ForEach에서 this 사용하기

by kakk789 2023. 1. 27.

 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();

반응형

댓글