[TIL] call, apply, bind 차이

ShallWeDance·2021년 9월 12일
0

TIL

목록 보기
16/17
post-thumbnail

call, apply, bind?

이 메소드들은 javasciprt에서 명시적으로 this를 바인딩 할 때 사용합니다.

call

call() 메소드는 주어진 this 값 및 각각 전달된 인수와 함께 함수를 즉시 호출합니다.
call()을 사용하려는 함수에 파라미터가 있는 경우 콤마(,)로 연결하여 전달해주면 됩니다.

// 구문
fun.call(thisArg[, arg1[, arg2[, ...]]]);

// 예시
const person1 = {firstName: 'Jon', lastName: 'Kuperman'};
const person2 = {firstName: 'Kelly', lastName: 'King'};

function say(greeting) {
    console.log(greeting + ' ' + this.firstName + ' ' + this.lastName);
}

say.call(person1, 'Hello'); // Hello Jon Kuperman
say.call(person2, 'Hello'); // Hello Kelly King

apply

apply() 메서드는 주어진 this 값과 배열(또는 유사 배열 객체)로 제공되는 arguments 로 함수를 호출합니다.
이 함수의 구문은 거의 call() 구문과 유사합니다. 근본적인 차이점은 call() 은 함수에 전달될 인수 리스트를 받는데 비해, apply() 는 인수들의 단일 배열을 받는다는 점입니다.

// 구문
func.apply(thisArg, [argsArray]);

// 예시
const person1 = {firstName: 'Jon', lastName: 'Kuperman'};
const person2 = {firstName: 'Kelly', lastName: 'King'};

function say(greeting) {
    console.log(greeting + ' ' + this.firstName + ' ' + this.lastName);
}

say.apply(person1, ['Hello']); // Hello Jon Kuperman
say.apply(person2, ['Hello']); // Hello Kelly King

bind

bind() 메소드가 호출되면 새로운 함수를 생성합니다. 그렇기 때문에 bind() 함수 사용 시 바로 함수가 호출되지 않습니다. 받게되는 첫 인자의 value로는 this 키워드를 설정하고, 이어지는 인자들은 바인드된 함수의 인수에 제공됩니다.

// 구문
func.bind(thisArg[, arg1[, arg2[, ...]]]);

// 예시
const person1 = {firstName: 'Jon', lastName: 'Kuperman'};
const person2 = {firstName: 'Kelly', lastName: 'King'};

function say(greeting) {
    console.log(greeting + ' ' + this.firstName + ' ' + this.lastName);
}

const sayHelloJon = say.bind(person1);
const sayHelloKelly = say.bind(person2);

sayHelloJon(); // Hello Jon Kuperman
sayHelloKelly(); // Hello Kelly King

Reference

javascript call, apply, bind 차이점! 알짜만 빼먹기!
MDN_Function.prototype.call()
MDN_Function.prototype.apply()
MDN_Function.prototype.bind()

0개의 댓글