티스토리 뷰

Javascript

call, apply 그리고 bind

cs09g 2020. 7. 1. 22:30
반응형

call, apply, bind는 함수의 실행 컨텍스트(this)를 지정하는데 유용한 메소드이다.

this란 함수가 실행된 환경을 나타내는 것으로 보통은 함수가 실행되는 시점에 결정되며 이를 this가 함수에 바인딩된다고 한다.

여기서 바인딩 되는 this를 지정할 수 있게 해주는 것이 call, apply 이고, 바인딩되는 시점을 실행 시점으로부터 독립시켜주는 것이 bind 이다.

 

call, apply 의 경우 호출 즉시 this가 바인딩되고 함수가 실행된다. 차이점은 파라미터가 나열형(call)이냐 배열(apply)이냐 정도이다.


this를 지정한다는 것은 아무 값이나 지정할 수 있다는 의미는 아니고, 다음과 같이 생성자 체이닝으로 this를 통해 다른 메소드의 프로퍼티를 가져오는 효과를 얻을 수 있다.

function Product(name, price) {
  this.name = name;
  this.price = price;
}

function Food(name, price) {
  Product.call(this, name, price); // equivalent to `Product.apply(this, [name, price]);`
  this.category = "food";
}

const burger = new Food("burger", 10);
/*
  burger = {
    name: "burger",
    price: 10,
    category: "food",
  };
*/

Food에서 Product.call을 호출하는 순간 this는 Product가 아닌 Food로써 바인딩되므로, Food의 프로퍼티로 name, price가 설정되는 것이다.

Product와 무슨 연관이 있는거 아닌가하는 의문이 든다면, burger의 prototype을 비교해보면 된다.

burger.__proto__ === Product.prototype // false
burger.__proto__ === Food.prototype // true

반면에 위와 달리 연관성을 주입하려면 다음과 같이 작성해볼 수 있을 것이다.

function Product(name, price) {
  this.name = name;
  this.price = price;
}

function Food(name, price) {
  const product = new Product(name, price);
  product.category = "food";
  return product;
}

const burger = new Food("burger", 10);

 

burger의 출력물은 동일하지만 이 경우 burger는 Product가 된다.

burger.__proto__ === Product.prototype // true
burger.__proto__ === Food.prototype // false

bind는 첫 번째 파라미터로 전달한 변수에 bind를 호출한 시점의 this를 설정한다. 호출 시 함수가 반환되는데, 이 함수를 호출하면 바인딩한 메소드가 실행된다. bind를 사용하여 위 예시를 구현하면 다음과 같다.

function Product(name, price) {
  this.name = name;
  this.price = price;
}

function Food(name, price) {
  const product = Product.bind(this, name, price);
  this.category = "food";
  product();
}

const burger = new Food("burger", 10);

결과는 동일하다.

반응형
댓글