rustandbone Developer

모던 JS deep dive 2회차 챕터 22 this

모던 JS deep dive 2회차

22. this

22.1 this 키워드

객체 : 상태를 나타내는 프로퍼티동작을 나타내는 메서드를 하나의 논리적인 단위로 묶은 복합적인 자료구조

메서드는 자신이 속한 객체의 상태, 즉 프로퍼티를 참조하고 변경할 수 있어야 함.
=> 메서드는 자신이 속한 객체를 가리키는 식별자를 참조할 수 있어야 함

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

this는 자바스크립트 엔진에 의해 암묵적으로 생성, 코드 어디서든 참조 가능함. 함수를 호출하면 arguments 객체와 this가 암묵적으로 함수 내부에 전달됨. this가 가리키는 값은 함수 호출 방식에 의해 동적으로 결정됨.

this 바인딩 : 바인딩이란 식별자와 값을 연결하는 과정 의미. this 바인딩은 this(키워드로 분류되지만 식별자 역할을 함)와 this가 가리킬 객체를 바인딩하는 것.

// 객체 리터럴
const circle = {
  radius: 5,
  getDiameter() {
    // this는 메서드를 호출한 객체를 가리킨다.
    return 2 * this.radius;
  },
};

console.log(circle.getDiameter()); // 10

=> 객체 리터럴의 메서드 내부에서의 this는 메서드를 호출한 객체, 즉 circle를 가리킴

// 생성자 함수
function Circle(radius) {
  // this는 생성자 함수가 생성할 인스턴스를 가리킨다.
  this.radius = radius;
}

Circle.prototype.getDiameter = function () {
  // this는 생성자 함수가 생성할 인스턴스를 가리킨다.
  return 2 * this.radius;
};

// 인스턴스 생성
const circle = new Circle(5);
console.log(circle.getDiameter()); // 10

=> 생성자 함수 내부의 this는 생성자 함수가 생성할 인스턴스를 가리킴.

=> this는 상황에 따라 가리키는 대상이 다름

자바, C++ 같은 클래스 기반 언어의 this는 언제나 클래스가 생성하는 인스턴스를 가리킴.
자바스크립트의 this는 함수가 호출되는 방식에 따라 this에 바인딩될 값, 즉 this 바인딩이 동적으로 결정됨.

this는 코드 에디에서든 참조 가능. 전역에서도, 함수 내부에서도 참조 가능

// this는 어디서든지 참조 가능하다.
// 전역에서 this는 전역 객체 window를 가리킨다.
console.log(this); // window

function square(number) {
  // 일반 함수 내부에서 this는 전역 객체 window를 가리킨다.
  console.log(this); // window
  return number * number;
}
square(2);

일반적으로 this는 객체의 메서드 내부 또는 생성자 함수 내부에서만 의미가 있음. 따라서 strict mode가 적용된 일반 함수 내부의 this에는 undefined가 바인딩됨 => 일반 함수 내부에서 this를 사용할 필요가 없기 때문.

22.2 함수 호출 방식과 this 바인딩

this 바인딩(this에 바인딩될 값)은 함수 호출 방식, 즉 함수가 어떻게 호출되었는지에 따라 동적으로 결정됨.

렉시컬 스코프와 this 바인딩은 결정 시기가 다름 : 함수의 상위 스코프를 결정하는 방식인 렉시컬 스코프는 함수 정의가 평가되어 함수 객체가 생성되는 시점에 상위 스코프를 결정. this 바인딩은 함수 호출 시점에 결정됨.

  1. 함수 호출 방식
  2. 일반 함수 호출
  3. 메서드 호출
  4. 생성자 함수 호출
  5. Function.prototype.apply/call/bind 메서드에 의한 간접 호출

22.2.1 일반 함수 호출

function foo() {
  console.log("foo's this: ", this); // window
  function bar() {
    console.log("bar's this: ", this); // window
  }
  bar();
}
foo();

기본적으로 this에는 전역 객체(window)가 바인딩됨.

중첩 함수를 일반 함수로 호출하면 함수 내부의 this에는 전역 객체가 바인딩됨. 일반 함수에 this는 의미가 없음.

function foo() {
  "use strict";

  console.log("foo's this: ", this); // undefined
  function bar() {
    console.log("bar's this: ", this); // undefined
  }
  bar();
}
foo();

strict mode가 적용된 일반 함수 내부의 this에는 undefined가 바인딩됨

// var 키워드로 선언한 전역 변수 value는 전역 객체의 프로퍼티다.
var value = 1;
// const 키워드로 선언한 전역 변수 value는 전역 객체의 프로퍼티가 아니다.
// const value = 1;

const obj = {
  value: 100,
  foo() {
    console.log("foo's this: ", this); // {value: 100, foo: ƒ}
    console.log("foo's this.value: ", this.value); // 100

    // 메서드 내에서 정의한 중첩 함수
    function bar() {
      console.log("bar's this: ", this); // window
      console.log("bar's this.value: ", this.value); // 1
    }

    // 메서드 내에서 정의한 중첩 함수도 일반 함수로 호출되면 중첩 함수 내부의 this에는 전역 객체가 바인딩된다.
    bar();
  },
};

obj.foo();

=> 메서드 내에서 정의한 중첩 함수도 일반 함수로 호출되면 중첩 함수 내부의 this에는 전역 객체가 바인딩됨

var value = 1;

const obj = {
  value: 100,
  foo() {
    // this 바인딩(obj)을 변수 that에 할당한다.
    const that = this;

    // 콜백 함수 내부에서 this 대신 that을 참조한다.
    setTimeout(function () {
      console.log(that.value); // 100
    }, 100);
  },
};

obj.foo();

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

=> 일반 함수로 호출된 모든 함수(중첩 함수, 콜백 함수 포함) 내부의 this에는 전역 객체가 바인딩됨

중첩 함수 또는 콜백 함수의 this가 전역 객체를 바인딩하는 것은 문제가 됨. 중첩 함수나 콜백 함수는 헬퍼 함수의 역할을 하는 것인데, 외부 함수인 메서드의 this와 중첩 함수나 콜백 함수의 this가 일치하지 않는다는 것은 헬퍼 함수로 동작하기 어려움.

var value = 1;

const obj = {
  value: 100,
  foo() {
    // this 바인딩(obj)을 변수 that에 할당한다.
    const that = this;

    // 콜백 함수 내부에서 this 대신 that을 참조한다.
    setTimeout(function () {
      console.log(that.value); // 100
    }, 100);
  },
};

obj.foo();

=> 중첩 함수나 콜백 함수의 this 바인딩을 메서드의 this 바인딩과 일치시키기 위한 방법

var value = 1;

const obj = {
  value: 100,
  foo() {
    // 콜백 함수에 명시적으로 this를 바인딩한다.
    setTimeout(
      function () {
        console.log(this.value); // 100
      }.bind(this),
      100
    );
  },
};

obj.foo();

=> 자바스크립트는 this를 명시적으로 바인딩할 수 있는 Function.prototype.apply/call/bind 메서드를 제공

var value = 1;

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

obj.foo();

=> 화살표 함수를 사용해서 this 바인딩을 일치시킬 수도 있음.

22.2.2 메서드 호출

메서드 내부의 this에는 메서드를 호출한 객체, 즉 메서드를 호출할 때 메서드 이름 앞의 마침표 연산자 앞에 기술한 객체가 바인딩됨
=> 주의 : 메서드 내부의 this는 메서드를 소유한 객체가 아닌 메서드를 호출한 객체에 바인딩된다는 것

const person = {
  name: 'Lee',
  getName() {
    // 메서드 내부의 this는 메서드를 호출한 객체에 바인딩된다.
    return this.name;
  }
};

// 메서드 getName을 호출한 객체는 person이다.
console.log(person.getName()); // Lee

---

const anotherPerson = {
  name: 'Kim'
};

// getName 메서드를 anotherPerson 객체의 메서드로 할당
anotherPerson.getName = person.getName;

// getName 메서드를 호출한 객체는 anotherPerson이다.
console.log(anotherPerson.getName()); // Kim

// getName 메서드를 변수에 할당
const getName = person.getName;

// getName 메서드를 일반 함수로 호출
console.log(getName()); // ''
// 일반 함수로 호출된 getName 함수 내부의 this.name은 브라우저 환경에서 window.name과 같다.
// 브라우저 환경에서 window.name은 브라우저 창의 이름을 나타내는 빌트인 프로퍼티이며 기본값은 ''이다.
// Node.js 환경에서 this.name은 undefined다.

22.2.3 생성자 함수 호출

생성자 함수 내부의 this에는 생성자 함수가 (미래에) 생성할 인스턴스가 바인딩됨

// 생성자 함수
function Circle(radius) {
  // 생성자 함수 내부의 this는 생성자 함수가 생성할 인스턴스를 가리킨다.
  this.radius = radius;
  this.getDiameter = function () {
    return 2 * this.radius;
  };
}

// 반지름이 5인 Circle 객체를 생성
const circle1 = new Circle(5);
// 반지름이 10인 Circle 객체를 생성
const circle2 = new Circle(10);

console.log(circle1.getDiameter()); // 10
console.log(circle2.getDiameter()); // 20

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

Function.prototype.apply / Function.prototype.call 메서드는 this로 사용할 객체인수 리스트를 인수로 전달받아 함수를 호출함

  • apply
    • 작성법 : fn.apply(thisArg, [argsArray])
    • this 인자를 첫번째 인자로 받고, 두번째 인자로는 배열을 받음
  • call
    • 작성법 : fn.call(thisArg[, arg1[, arg2[, …]]])
    • this 인자를 첫번째 인자로 받고, 두번째 인자부터는 배열이 아닌 각 인자로 받음

=> 두 메서드의 본질적인 기능은 함수를 호출하는 것. 함수를 호출하면서 첫 번째 인수로 전달한 특정 객체를 호출한 함수의 this에 바인딩함

function getThisBinding() {
  return this;
}

// this로 사용할 객체
const thisArg = { a: 1 };

console.log(getThisBinding()); // window

// getThisBinding 함수를 호출하면서 인수로 전달한 객체를 getThisBinding 함수의 this에 바인딩한다.
console.log(getThisBinding.apply(thisArg)); // {a: 1}
console.log(getThisBinding.call(thisArg)); // {a: 1}

=> getThisBining 함수에 인수를 전달하지 않음

function getThisBinding() {
  console.log(arguments);
  return this;
}

// this로 사용할 객체
const thisArg = { a: 1 };

// getThisBinding 함수를 호출하면서 인수로 전달한 객체를 getThisBinding 함수의 this에 바인딩한다.
// apply 메서드는 호출할 함수의 인수를 배열로 묶어 전달한다.
console.log(getThisBinding.apply(thisArg, [1, 2, 3]));
// Arguments(3) [1, 2, 3, callee: ƒ, Symbol(Symbol.iterator): ƒ]
// {a: 1}

// call 메서드는 호출할 함수의 인수를 쉼표로 구분한 리스트 형식으로 전달한다.
console.log(getThisBinding.call(thisArg, 1, 2, 3));
// Arguments(3) [1, 2, 3, callee: ƒ, Symbol(Symbol.iterator): ƒ]
// {a: 1}
  • apply 메서드는 호출할 함수의 인수를 배열로 묶어 전달
  • call 메서드는 호출할 함수의 인수를 쉼표로 구분한 리스트 형식으로 전달
function getThisBinding() {
  return this;
}

// this로 사용할 객체
const thisArg = { a: 1 };

// bind 메서드는 첫 번째 인수로 전달한 thisArg로 this 바인딩이 교체된
// getThisBinding 함수를 새롭게 생성해 반환한다.
console.log(getThisBinding.bind(thisArg)); // getThisBinding
// bind 메서드는 함수를 호출하지는 않으므로 명시적으로 호출해야 한다.
console.log(getThisBinding.bind(thisArg)()); // {a: 1}

=> bind 메서드는 함수를 호출하지 않고 this로 사용할 객체만 전달. this와 메서드 내부의 중첩 함수 또는 콜백 함수의 this가 불일치하는 문제를 해결하기 위해 유용하게 사용

  • 함수 호출 방식 : this 바인딩
    • 일반 함수 호출 : 전역 객체
    • 메서드 호출 : 메서드를 호출한 객체
    • 생성자 함수 호출 : 생성자 함수가 (미래에) 생성할 인스턴스
    • Function.prototype.apply/call/bind 메서드에 의한 간접 호출 : Function.prototype.apply/call/bind 메서드에 첫번째 인수로 전달한 객