:ledger: 함수 바인딩에 대해 알아보자

JavaScript에서 함수 바인딩(binding)이란, 함수 내부의 this 값을 명시적으로 지정하는 기법을 의미한다. 특히, 객체의 메서드를 콜백으로 전달하거나 함수가 호출될 컨텍스트를 잃었을 때 유용하다.

:one: 왜 함수 바인딩이 필요한가?

일반적으로 메서드 내부의 this는 호출하는 객체를 가리킨다. 하지만 특정 상황에서는 this의도치 않은 값을 참조할 수 있다. 대표적인 예로 콜백 함수로 객체의 메서드를 전달할 때 발생한다.

// 문제 예시
const user = {
  name: "kim",
  greet() {
    console.log(`Hello, ${this.name}!`);
  },
};

setTimeout(user.greet, 1000); // 출력: "Hello, undefined!"

위 코드에서 setTimeoutuser.greet를 전달했지만, thisuser를 가리키지 않고 전역 객체(브라우저에서는 window, Node.js에서는 global)를 참조한다. 이처럼 함수의 컨텍스트가 변할 때 this가 바뀌는 문제를 해결하기 위해 함수 바인딩이 필요하다.

:two: bind() 메서드

bind() 메서드는 함수를 호출하지 않고, 새로운 함수를 반환하며, 반환된 함수의 this를 지정한다.

// 문법
const boundFunction = func.bind(thisArg[, arg1, arg2, ...]);
  • thisArg: 함수 내부에서 사용할 this
  • arg1, arg2, ...: 함수 호출 시 사용할 기본 인자

:pushpin: 2-1) 예제

// 예제 1
const user = {
  name: "Ming",
  greet() {
    console.log(`Hello, ${this.name}!`);
  },
};

const boundGreet = user.greet.bind(user);
setTimeout(boundGreet, 1000); // "Hello, Ming!"

// 예제 2
function multiply(a, b) {
  return a * b;
}

const double = multiply.bind(null, 2); // 첫 번째 인자를 2로 고정
console.log(double(5)); // 출력: 10

:three: call() 메서드

call() 메서드는 함수를 즉시 실행하며, 첫 번째 인자로 this를 지정한다.

:pushpin: 3-1) 예제

const user = {
  name: "Ming",
};

function greet(greeting) {
  console.log(`${greeting}, ${this.name}!`);
}

greet.call(user, "Hello"); //: "Hello, Ming!"

:four: 바인딩이 필요한 주요 사례를 알아봦

:pushpin: 4-1) 이벤트 핸들러

이벤트 핸들러에서 객체의 메서드를 호출하면 this가 이벤트 객체를 참조하는 경우가 많다. 이를 해결하기 위해 bind를 사용할 수 있다.

class Button {
  constructor(label) {
    this.label = label;
  }

  handleClick() {
    console.log(`Button ${this.label} clicked!`);
  }
}

const btn = new Button("Submit");
document
  .querySelector("button")
  .addEventListener("click", btn.handleClick.bind(btn));

:pushpin: 4-2) 객체 메서드 전달

객체의 메서드를 다른 함수에 콜백으로 전달할 때, bindthis를 고정해야 올바르게 동작한다.

const timer = {
  time: 0,
  start() {
    setInterval(
      function () {
        this.time++;
        console.log(this.time);
      }.bind(this),
      1000
    );
  },
};

timer.start();

:five: Arrow Function과 바인딩

화살표 함수(Arrow Function)this를 외부 컨텍스트에서 가져오기 때문에, 별도로 바인딩하지 않아도 된다.

  • 화살표 함수는 함수의 this가 상위 스코프를 따르므로, 콜백 함수나 중첩 함수에서 유용하다.
const user = {
  name: "Kim",
  greet() {
    setTimeout(() => {
      console.log(`Hello, ${this.name}!`); // this는 user를 참조
    }, 1000);
  },
};

user.greet(); // "Hello, Kim!"

:fire: 요약

메서드 역할 특징
bind() 함수의 this를 고정한 새 함수 반환 함수 호출 지연, 부분 적용 가능
call() 함수 호출 시 this 지정 인자를 직접 나열하여 전달
apply() 함수 호출 시 this 지정 인자를 배열 형태로 전달

:pushpin: 참고 문서

태그:

카테고리: ,

업데이트: