[JavaScript] this

배고픈메꾸리·2021년 1월 19일
0

Advanced JavaScript

목록 보기
10/10
post-thumbnail

this


this는 자바스크립트의 굉장히 혼란스러운 개념 중 하나이다. 이번 시간에는 this에 대해서 알아보자.

this is the object that the function is a property of.

this 는 위에 써있는 대로 함수를 property로 갖는 객체이다.

사실 우리는 this를 이전에 배웠던 적이 있다.

전역 컨텍스트의 creation phase에서 Global Object가 생성되고 this가 Global Object로 바인딩 된다고 하였다. 개발자 도구 콘솔창에 this 를 입력해보자

앞서 말했듯 window 객체가 출력되는 것을 알 수 있다.

function a(){
  console.log(this);
}

그럼 위와 같은 코드는 어떤 결과를 출력할까?? 정답은 바로 window 객체이다.


function a는 전역 컨텍스트 에서 선언하여 실행되고 있다. this의 정의를 살펴 보면 함수를 property로 갖는 객체 인데 a함수는 전역 컨텍스트의 property중 하나이고 따라서 a를 property로 갖는 객체인 window 가 출력되는 것이다.

또 다른 예제를 살펴보자.

const obj = {
  name : "Billy",
  sing : function(){
    return "lalala " + this.name;
  }
}
obj.sing();

function 함수의 return 문에 있는 this.name 을 살펴보자. this의 정의에 따라서 함수 function을 property 로 갖는 객체는 obj이다. obj 객체에서 name을 받아와서 출력한 다면 결과값은 Billy.name 이 출력될 것임을 알 수 있다.

그렇다면 이렇게 어려운 this라는 개념을 사용해서 얻을 수 있는 이점을 무엇이 있을까??

1. 같은 this를 가지고 있는 Sibling Property에 접근 가능하다.

const obj ={
  name : 'Billy',
  sing() {
    return 'lalala ' + this.name
  },
  singAgain(){
    // return 'lalala ' + this.name + '!'
    return this.sing() + '!'
  }
}

obj.singAgain(); // lalala Billy!

singsingAgain 이라는 메소드가 있다고 하자. singAgain 메소드를 이용해서 sing 메소드의 결과값에 추가적인 작업을 하고 싶은 상황이다. 이럴 경우 this 키워드를 사용해서 Sibling Property에 접근하여 결과 값을 가져올 수 있게 되고 , 코드를 반복해서 작성하지 않아도 되는 이점이 있다.

2. 같은 코드를 여러 객체에서 사용할 수 있다.

function importantPerson(){
  console.log(this.name)
}

const name = "Sunny";
const obj1 = {
  name : "Cassy",
  importantPerson : importantPerson
}
const obj2 = {
  name : "Jacob",
  importantPerson : importantPerson
}

importantPerson() // "Sunny"
obj1.importantPerson() // Cassy
obj2.importantPerson() // Jacob

importantPerson 함수는 같은 코드임에도 어떤 객체에서 호출하냐에 따라 다른 결과값을 출력한다. 이렇듯 this를 쓰면 코드의 재사용성을 높일 수 있다.

결론 : this == Who called me?

동적 스코프 vs 정적 스코프

추가중

profile
FE 개발자가 되자

0개의 댓글