Javascript this 키워드

YuJin Lee·2021년 11월 30일
0

Javascript

목록 보기
22/22

전역에서 this

console.log(this)

결과: Window

일반 함수 안에서 this

function 함수(){
  console.log(this)
}
함수()

결과: Window ('use strict' 모드에서는 undefined)

오브젝트 안에서 this

const object1 = {
  data: 'Lee',
  function1: function(){ console.log(this) }
}
object1.function1()

결과: 메소드를 가지고 있는 object1 { data: 'kim', function1: [Function: function1] }

const object2 = {
  data: {
    function2: function(){
      console.log(this)
    }
  }
}
object2.data.function2();

결과: 메소드를 갖고 있는 object2.data { function2: [Function: function2] }

즉, this는 나를 담고 있는 object를 뜻한다.


이벤트리스너 안에서 this

이벤트리스너 안에서는 this가 e.currentTarget과 같은 역할을 한다.
html 태그가 나오는데, 이벤트가 동작하고 있는 요소를 나타낸다.

만약 이벤트리스너 안의 forEach 반복문에서 this가 실행됐다면, Window가 출력된다.
forEach 안의 콜백함수는 전역에 선언되어있는 함수이기 때문이다.

그렇기 때문에 object의 함수 안의 forEach 반복문 안에서 this가 실행되었어도 Window가 출력된다.

arrow function을 사용할 때 this

이 때 arrow function을 사용한다면 어떻게 될까?
arrow function은 내부의 this 값을 변화시키지 않기 때문에 외부 this 값을 그대로 재사용 가능하다.

const object2 = {
  data: {
    function2: () => {
      console.log(this)
    }
  }
}
object2.data.function2();

결과: Window.
함수 밖에 있는 값을 그대로 쓴다.

만약 이벤트리스너에서 arrow function을 사용했는데,
그 함수 안에서 e.currentTarget을 사용하고 싶다면,
this를 사용하면 안되고 e.currentTarget 키워드를 그대로 사용해야 한다.

예시

1

const person = {
  name: '손흥민',
  sayhi(){
    console.log(`안녕 나는 ${this.name}`);
  }
}

person.sayhi();

object 안의 함수에서 object 내부의 값을 불러오기 위해 this를 사용했다.
이 때 arrow function을 사용한면 안 된다.

2

const data = {
  number: [1,2,3,4,5],
}

data.sumAll = function(){
  let result = 0;
  data.number.forEach(function(a){    
    result = result + a;
  });
  console.log(result);
}

data.sumAll();

object 안에 함수를 선언했다.
이 때도 object 내부의 number 값을 불러오기 위해 this를 사용했으며 arrow function을 사용할 수 없다.

3

document.getElementById("button").addEventListener("click", function () {
  setTimeout(() => {
    console.log(this.innerHTML);
  }, 1000);
});

버튼을 누르면 1초 뒤에 버튼 안의 내용이 콘솔에 뜨도록 한다.
이 때는 function 키워드를 쓰면 this가 콜백함수를 가르키므로 arrow function을 써야한다.

profile
배운 것을 기록하는 곳 💻🙂

0개의 댓글