ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Javascript) this
    Javascript 2022. 8. 2. 19:42

    동작을 나타내는 메서드는 자신이 속한 객체의 상태, 즉 프로퍼티를 참조하고 변경할 수 있어야 한다. 이 때 메서드가 자신이 속한 객체의 프로퍼티를 참조하려면 먼저 자신이 속한 객체를 가리키는 식별자를 참조할 수 있어야 한다

     

    객체 리터럴 방식으로 생성한 객체의 경우 메서드 내부에서 메서드 자신이 속한 객체를 가리키는 식별자를 재귀적으로 참조할 수 있다.

    const circle = {
      radius: 5,
      getDiameter() {
        return 2 * circle.radius;
      },
    };
    
    console.log(circle.getDiameter());

     

    생성자 함수 방식으로 인스턴스를 생성하는 경우를 생각해보자.

    function Circle(radius) {
      // 이 시점에는 생성자 함수 자신이 생성할 인스턴스를 가리키는 식별자를 알 수 없다.
      ???.radius = radius;
    }
    
    // 생성자 함수로 인스턴스를 생성하려면 먼저 생성자 함수를 정의해야 함
    const circle = new Circle(5);

    생성자 함수를 정의하는 시점에는 아직 인스턴스를 생성하기 이전이므로 생성자 함수가 생성할 인스턴스를 가리키는 식별자를 알 수 없다.

     

    따라서 자신이 속한 객체 또는 자신이 생성할 인스턴스를 가리키는 특수한 식별자가 필요한데 이를 위해 자바스크립트는 this라는 특수한 식별자를 제공한다.

     

    this는 자신이 속한 객체 또는 자신이 생성할 인스턴스를 가리키는 자기 참조 변수다. this를 통해 자신이 속한 객체 또는 자신이 생성할 인스턴스의 프로퍼티나 메서드를 참조할 수 있다.

     

    this가 가리키는 값, 즉 this 바인딩은 함수 호출 방식에 의해 동적으로 결정된다.

     

    위의 코드를 this를 사용한 코드로 수정하면 다음과 같다.

    const circle = {
      radius: 5,
      getDiameter() {
      // this는 메서드를 호출한 객체를 가리킨다.
        return 2 * this.radius;
      },
    };
    
    console.log(circle.getDiameter()); // 10
    function Circle(radius) {
      // this는 생성자 함수가 생성할 인스턴스를 가리킨다.
      this.radius = radius;
    }
    
    // 인스턴스 생성
    const circle = new Circle(5);
    console.log(circle.radius); // 5

     

    ⭐⭐Javascript의 this는 함수가 호출되는 방식에 따라 this에 바인딩 될 값,

    this 바인딩이 동적으로 결정된다 ! === 함수 호출 시점에 결정

    브라우저 상의 this는 전역객체 window를 가리킨다.

     

    일반 함수 내부에서 this는 전역 객체 window를 기리킨다.

    const person = {
      name: "choo",
      getName() {
        // 메서드 내부에서 this는 메서드를 호출한 객체를 기리킨다.
        console.log(this);
        return this.name;
      },
    };
    
    console.log(person.getName());
    // { name: 'choo', getName: [Function: getName] }
    // choo
    
    function Person(name) {
      // 생성자 함수 내부에서 this는 생성자 함수가 생성할 인스턴스를 가리킨다.
      this.name = name;
      console.log(this);
    }
    
    const me = new Person("choo"); // Person { name: 'choo' }

    함수 호출 방식에 따른 this 바인딩

     

    함수를 호출하는 방식은 크게 4가지로 나눌 수 있다.

     

    1. 일반 함수 호출

    2. 메서드 호출

    3. 생성자 함수 호출

    4. Function.prototype.apply/call/bind 메서드에 의한 간접 호출

     

    1. 일반 함수 호출

    기본적으로 this에는 전역 객체가 바인딩된다.

    전역 함수는 물론이고 중첩 함수를 일반 함수로 호출하면 함수 내부의 this에는 전역 객체가 바인딩된다.

    this는 객체의 프로퍼티나 메서드를 참조하기 위한 자기 참조 변수이므로 객체를 생성하지 않는 일반 함수에서 this는 의미가 없다.

     

    콜백 함수가 일반 함수로 호출 된다면 콜백 함수 내부의 this에도 전역 객체가 바인딩됨. 어떠한 함수라도 일반함수로 호출되면 this에 전역 객체가 바인딩된다.

    메서드 내부의 중첩 함수나 콜백 함수의 this 바인딩을 메서드의 this 바인딩과 일치시키기 위한 방법은 다음과 같다.

    var value = 1;
    const obj = {
      value: 100,
      foo() {
        const that = this;
        setTimeout(function () {
          console.log(that.value);
        }, 1000);
      },
    };
    obj.foo(); // 100
    var value = 1;
    const obj = {
      value: 100,
      foo() {
        // 화살표 함수 내부의 this는 상위 스코프의 this를 가리킨다.
        setTimeout(() => console.log(this.value), 1000);
      },
    };
    obj.foo(); // 100

     

    2. 메서드 호출

    메서드 내부의 this는 메서드를 소유한 객체가 아닌 메서드를 호출한 객체에 바인딩된다.

    const person = {
      name: "choo",
      getName() {
        return this.name;
      },
    };
    // 메서드 getName을 호출한 객체는 person이다.
    console.log(person.getName()); // choo
    
    const anotherPerson = {
      name: "KIM",
    };
    anotherPerson.getName = person.getName;
    // getName을 호출한 객체는 anotherPerson이다.
    console.log(anotherPerson.getName()); // KIM
    
    function Person(name) {
      this.name = name;
    }
    
    Person.prototype.getName = function () {
      return this.name;
    };
    
    const me = new Person("CHOO");
    // getName 메서드를 호출한 객체는 me다.
    console.log(me.getName()); // CHOO
    
    Person.prototype.name = "KIM";
    // getName 메서드를 호출한 객체는 Person.prototype이다.
    console.log(Person.prototype.getName()); // KIM

    위의 예시를 통해 this에 바인딩될 객체는 호출 시점에 결정된다는 것을 알 수 있다.

     

    3. 생성자 함수 호출

    function Circle(radius) {
      // 생성자 함수 내부의 this는 생성자 함수가 생성할 인스턴스를 가리킨다.
      this.radius = radius;
      this.getDiameter = function () {
        return 2 * this.radius;
      };
    }
    
    const circle1 = new Circle(5);
    const circle2 = new Circle(10);
    
    console.log(circle1.getDiameter()); // 10
    console.log(circle2.getDiameter()); // 20

     

    4. Function.prototype.apply/call/bind 메서드에 의한 간접 호출

    function getThisBinding() {
      console.log(arguments);
      return this;
    }
    
    console.log(getThisBinding()); // window
    
    // this로 사용할 객체
    const thisArg = { a: 1 };
    
    // apply, call 메서드는 함수를 호출하면서 첫 번째 인수로 전달한
    // 특정 객체를 호출한 함수의 this에 바인딩한다.
    console.log(getThisBinding.apply(thisArg)); // {a: 1}
    console.log(getThisBinding.call(thisArg)); // {a: 1}
    
    // apply 메서드는 호출할 함수의 인수를 배열로 묶어 전달한다.
    console.log(getThisBinding.apply(thisArg, [1, 2, 3]));
    // [Arguments] { '0': 1, '1': 2, '2': 3 }
    // { a: 1 }
    
    // call 메서드는 호출할 함수의 인수를 쉼표로 구분한 리스트 형식으로 전달한다.
    console.log(getThisBinding.call(thisArg, 1, 2, 3));
    // [Arguments] { '0': 1, '1': 2, '2': 3 }
    // { a: 1 }
    
    // bind 메서드는 함수에 this로 사용할 객체를 전달한다.
    // bind 메서드는 함수를 호출하지 않으므로 명시적으로 호출해야 한다.
    console.log(getThisBinding.bind(thisArg)());
    // [Arguments] {}
    // { a: 1 }

     

    'Javascript' 카테고리의 다른 글

    Javascript) 화살표 함수와 일반 함수의 차이  (0) 2022.08.16
    Javascript) 클래스  (0) 2022.08.16
    Javascript) 클로저  (0) 2022.08.13
    Javascript) 생성자 함수에 의한 객체 생성  (0) 2022.06.18
    Javascript) Property Arrtibute  (0) 2022.06.18

    댓글

Designed by Tistory.