본문 바로가기
개발/VANILLAJS

bind, apply ,call

by tsuyuoto 2024. 12. 14.
반응형

bind, apply, 그리고 call은 JavaScript에서 함수의 **this**를 제어하거나 함수의 실행 방식을 변경할 때 자주 사용되는 메서드입니다. 아래에서 하나씩 자세히 설명하겠습니다.

 

1. bind()

bind 메서드는 함수를 호출하지 않고, 새로운 this 컨텍스트를 바인딩한 새로운 함수를 반환합니다.

  • 사용법:
    func.bind(thisArg, ...args)
  • 매개변수:
    • thisArg: 새로운 this 값으로 사용할 객체.
    • ...args: (선택 사항) 새로운 함수 호출 시 사용할 기본 인자들.
  • 특징:
    • 함수를 바로 실행하지 않습니다.
    • 반환된 함수는 호출 시 항상 지정된 thisArg를 사용합니다.
const person = {
  name: "Alice",
  greet() {
    console.log(`Hello, my name is ${this.name}`);
  }
};

const greetFunction = person.greet.bind(person); // this를 person으로 바인딩
greetFunction(); // "Hello, my name is Alice"

const otherPerson = { name: "Bob" };
const greetOther = person.greet.bind(otherPerson);
greetOther(); // "Hello, my name is Bob"

 

예제: bind로 함수에 기본 인자 추가

function add(a, b) {
  return a + b;
}

const addFive = add.bind(null, 5); // 첫 번째 인자를 5로 고정
console.log(addFive(10)); // 15​

 

call()

call 메서드는 함수의 **this**를 특정 값으로 설정한 후, 즉시 실행합니다.

  • 사용법:
    func.call(thisArg, ...args)
  • 매개변수:
    • thisArg: 새로운 this 값으로 사용할 객체.
    • ...args: 함수 호출에 전달할 인자들.
  • 특징:
    • 함수가 즉시 실행됩니다.
    • 매개변수는 쉼표로 구분합니다.
function greet(greeting, punctuation) {
  console.log(`${greeting}, my name is ${this.name}${punctuation}`);
}

const person = { name: "Alice" };
greet.call(person, "Hello", "!"); // "Hello, my name is Alice!"

 

 

apply()

apply 메서드는 call과 비슷하지만, 인자를 배열 형태로 전달합니다.

  • 사용법:
    func.apply(thisArg, [args])
  • 매개변수:
    • thisArg: 새로운 this 값으로 사용할 객체.
    • [args]: 함수 호출에 전달할 인자를 배열로 전달.
  • 특징:
    • 함수가 즉시 실행됩니다.
    • 매개변수는 배열 형태로 전달합니다.
function greet(greeting, punctuation) {
  console.log(`${greeting}, my name is ${this.name}${punctuation}`);
}

const person = { name: "Bob" };
greet.apply(person, ["Hi", "?"]); // "Hi, my name is Bob?"

 

차이점 요약

메서드this 설정 방식인자 전달 방식실행 여부

bind 특정 객체로 바인딩 기본 인자 설정 가능 반환된 함수 호출 시 실행
call 특정 객체로 설정 쉼표로 구분 즉시 실행
apply 특정 객체로 설정 배열로 전달 즉시 실행

 

 

 

실제 활용 사례

  1. this 문제 해결
const button = {
  text: "Click me!",
  onClick() {
    console.log(this.text);
  }
};

const detachedOnClick = button.onClick;
detachedOnClick(); // undefined (this가 button을 가리키지 않음)

const boundOnClick = button.onClick.bind(button);
boundOnClick(); // "Click me!"

 

 

2. 배열의 최대값 계산 (apply 사용)
 
const numbers = [1, 5, 2, 9, 3];
const max = Math.max.apply(null, numbers);
console.log(max); // 9

 

3. 함수 커링

function multiply(a, b) {
  return a * b;
}

const double = multiply.bind(null, 2); // a를 2로 고정
console.log(double(5)); // 10

 

from GPT~

반응형