22장: this

​​​퀴즈

다음 결과는?

const obj = {
  value: 100,
  foo() {
    console.log("1: ", this);  
    console.log("2: ", this.value); 

    function bar() {
      console.log("3: ", this); 
      console.log("4: ", this.value); 
    }

    bar();
  }
};

obj.foo();

다음 결과는?

다음 결과는?

다음 결과는?

다음 결과는?

this 키워드

용어 정리

위치에 따라 바인딩이 달라진다

함수 호출 방식과 this 바인딩

  • this 바인딩은 함수 호출 방식에 따라 동적으로 결정된다.

  • 함수 호출 방식

    • 일반 함수 호출

    • 메서드 호출

    • 생성자 함수 호출

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

일반 함수 호출

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

  • 중첩함수를 일반 함수로 호출 this에는 전역 객체가 바인딩

콜백 함수 내부의 this는 전역 객체가 바인딩된다

  • 콜백 함수 내부에서 obj 객체 참조를 위한 임시? 해법

콜백 함수를 위한 명시적으로 바인딩

화살표 함수 내부의 this는 상위 스코프 this를 가리킨다

메서드 호출

메서드 내부의 this는 메서드를 호출한 객체에 바인딩된다

생성자 함수 호출

  • new 를 작성하지 않으면, 생성자 함수로 동작하지 않고 일반적인 함수 호출이 된다.

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

  • aplly/call/bind 차이?

    • aplly/call 의 본질적인 기능은 함수를 호출하는 것

    • [링크arrow-up-right] Call is a function that helps you change the context of the invoking function. In layperson's terms, it helps you replace the value of this inside a function with whatever value you want.

      • 안에 this를 변경

    • Apply is very similar to the call function. The only difference is that in apply you can pass an array as an argument list.

    • Bind is a function that helps you create another function that you can execute later with the new context of this that is provided.

  • aplly/call/bind 는 Function.prototype 의 메서드이다. 즉, 디폴트 상속이기에 모든 함수가 사용 가능.

아래처럼 apply/call 사용시, thisArg를 호출한 함수의 this 에 바인딩 한다.

  • 궁금, apply랑 call 비슷하면 배열까지 넘길수있는 apply 만 사용하면 되는거 아닌가?

bind는 apply/call 과 달리 함수를 호출하지 않는다. 첫번째 인수로 전달한 값으로 this 바인딩이 교체된 함수를 새롭게 생성해 반환한다.

bind는 메서드의 this 메서드와 내부의 중첩함수 또는 콜백함수의 this가 불일치하는 문제를 해결해주기도 한다.

추가 참고 자료

  • https://ko.javascript.info/constructor-new

Last updated