TIL

자바스크립트의 this

팝삐 2024. 8. 20. 14:07

This

  • 대부분의 경우 this의 값은 함수를 호출한 방법에 의해 결정된다.
  • 실행 중에는 할당으로 설정할 수 없고 함수를 호풀할 때마다 다를 수 있다.

ES5의 경우

  • 함수를 어떻게 호출했는 지 상관하지 않고 this 값을 설정할 수 있는 bind 메서드를 도입

ES6의 경우

  • 스스로의 this 바인딩을 제공하지 않는 화살표 함수를 추가

단독으로 쓴 this

  • 냅다 this를 호출하는 경우에 this는 global object를 가리킨다.
    • [object Window]
    'use strict';
     
    var x = this;
    console.log(x); //Window
    
    

함수 안에서 쓴 this

  • 함수 안에서 this는 함수의 주인에게 바인딩된다.
    • 함수의 주인 ⇒ window 객체
    function f1() {
      return this;
    }
    
    // 브라우저
    f1() === window; // true
    
    // Node.js
    f1() === global; // true
    
  • 엄격 모드에서 this 값은 실행 문맥에 진입하며 설정되는 값을 유지한다.
  • function f2() { "use strict"; // 엄격 모드 참고 return this; } f2() === undefined; // true

메서드 안에서 쓴 this

  • 일반 함수가 아니고 메서드인 경우
  • 메서드 호출 시 내부 코드에서 사용된 this는 해당 메서드를 호출한 객체로 바인딩된다.
  • var num = 0; function showNum() { console.log(this.num); } showNum(); //0 var obj = { num: 200, func: showNum, }; obj.func(); //200

이벤트 핸들러 안에서 쓴 this

  • 이벤트 핸들러에서 this는 이벤트를 받는 HTML 요소를 말한다.
  • var btn = document.querySelector('#btn') btn.addEventListener('click', function () { console.log(this); //#btn });

생성자 안에서 쓴 this

  • 생성자 함수가 생성하는 객체로 this가 바인딩 된다.
  • function Person(name) { this.name = name; } var kim = new Person('kim'); var lee = new Person('lee'); console.log(kim.name); //kim console.log(lee.name); //lee // new 키워드를 빼면 일반 함수 호출과 같아져서 window가 바인딩된다.

명시적 바인딩을 한 this

  • 명시적 바인딩은 짝을 짓는다.
    • apply()
      • apply()에서 매개변수로 받은 첫번째 값은 함수 내부에서 사용되는 this에 바인딩된다.
      • 두번째 값인 배열은 자신을 호출한 함수의 인자로 사용한다.
      func.apply(thisArg, [argsArray]);
      
      //인수들의 단일 배열을 받는다.
      
      function Character(name, level) {
        this.name = name;
        this.level = level;
      }
       
      function Player(name, level, job) {
        Character.apply(this, [name, level]);
        this.job = job;
      }
       
      var me = new Player('Nana', 10, 'Magician');
      
    • call()
      function whoisThis() {
        console.log(this);
      }
       
      whoisThis(); //window
       
      var obj = {
        x: 123,
      };
       
      whoisThis.call(obj); //{x:123}
      
    • ⇒ 인자를 this로 만드는 기능
  • 두 메서드 모두 보통 유사배열 객체에게 배열 메서드를 쓰고자 할 때 사용한다.

화살표 함수로 쓴 this

  • 화살표 함수에서 this는 자신을 감싼 정적 범위이다.
  • 전역 코드에서는 전역 객체를 가리킨다.
  • 화살표 함수는 전역 컨텍스트에서 실행되더라도 this를 새로 정의하지 않고, 바로 바깥 함수나 클래스의 this를 쓴다.
  • var Person = function (name, age) { this.name = name; this.age = age; this.say = function () { console.log(this); // Person {name: "Nana", age: 28} setTimeout(() => { console.log(this); // Person {name: "Nana", age: 28} console.log(this.name + ' is ' + this.age + ' years old'); }, 100); }; }; var me = new Person('Nana', 28); //Nana is 28 years old

Call / Apply / Bind

  • Call
    • this를 바인딩하면서 함수를 호출하는 것
    • 두번째 인자를 apply와 다르게 하나씩 넘기는 것
  • Apply
    • this를 바인딩하면서 함수를 호추라는 것
    • 두번째 인자가 배열
  • Bind
    • 함수를 호출하는 것이 아닌 this가 바인딩 된 새로운 함수를 리턴

출처

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/this

https://nykim.work/71