[JS] this의 상황별 동작

상황별로 다른 this의 동작에 대해 알아보자

JAVA와는 다르다!

  • java에서의 this는 클래스로부터 생성되는 인스턴스 중 현재 객체를 의미한다
  • javascript에서의 this는 함수의 현재 실행 문맥이다

4가지 실행 타입에 따른 this

함수 실행

  • 함수 실행에서의 this는 전역 객체다
    function log() {  
     console.log(this === window); // => true
     this.thiiiis = "thiiiis";
    }
    log(); 
    window.thiiiis; // => 'thiiiis' 
    
  • But, 엄격모드(strict)에서는 undefined다
    function log() {  
     'use strict'
     console.log(this === window); // => false
     this.thiiiis = "thiiiis";
    }
    log(); 
    window.thiiiis; // => 'Uncaught TypeError: Cannot set property 'thiiiis' of undefined'
    
  • 내부 함수에서의 this는 실행 컨텍스트에 따른다
    const names = {
      me : 'tuna',
      you : 'tutu',
      sayHi() {
          console.log(this);	// me
          function clap() {
              console.log(this);	// window
          }
          clap();
      }
    }
    names.sayHi();
    
  • 왜 그럴까 생각해본다면
    • sayHi()는 전역 함수가 아닌 객체 내의 메소드다
    • 그래서 sayHi()의 실행 컨텍스트는 names 객체다
    • 근데 clap()은 메소드인가 함수인가? sayHi() 메소드 내부에 정의된 함수
    • 함수에서의 this는 window, 즉 전역 객체를 따른다
  • 둘을 동일한 문맥으로 바꾸려면 call 메서드를 사용한다
    const names = {
      me : 'tuna',
      you : 'tutu',
      sayHi() {
          console.log('say Hi ' + this.you);	// say Hi tutu
          function clap() {
              console.log('clap ' + this.me);	// clap tuna
          }
          clap.call(this);
      }
    }
    names.sayHi();
    

메서드 실행

  • 메서드란 ? 객체의 속성으로 있는 함수
  • 속성 접근자를 통해 사용한다면 메서드, 바로 호출한다면 함수로 봐도 되겠다
  • 같은 기능이지만 this가 다르다
const thisPower = {
	sayPower() {
		console.log(this);
	}
}

thisPower.sayPower() 	// thisPower { ... }

const windowPower = thisPower.sayPower;
windowPower();			// window { ... }
  • windowPower()에서도 thisPower 객체를 this에 바인딩하는 방법은?
    • bind 메서드를 사용해 컨텍스트를 강제로 지정할 수 있다 (바람직한 방법인지는…)
const thisPower = {
	name : 'power',
	sayPower() {
		console.log(this.name);
	}
}

thisPower.sayPower() 	// power { ... }

const windowPower = thisPower.sayPower.bind(thisPower);
windowPower();			// power { ... }

생성자 실행

  • 생성자 실행은 표현식 앞에 new라는 키워드가 붙었을 때, 함수 객체로 계산되어 수행
  • 혹은 class로부터 객체 인스턴스를 만들때가 되겠지?
  • 이 곳에서의 this는 새로 만들어지는 객체 인스턴스다 (java랑 동일)

간접 실행

  • 함수가 .call()이나 apply() 메서드와 함께 호출될 때 수행
  • call()과 apply() 메서드는 위에서 보다시피 실행 컨텍스트를 특정한 컨텍스트로 지정한다

이제부터 this를 본다면

  • this가 어디로부터 오는가? 라는 생각보단

    함수가 어떻게 실행되는가? 라고 사고 방식을 바꾸자

 Date: 
 Tags:  JS