[JS] apply, call

게코젤리·2023년 5월 30일
0

apply, call은 함수를 특정 객체에 연결하고 호출하는 데 사용된다. 이들 메소드의 첫 번째 인자는 함수가 호출될 때 this의 값이 된다.

두 메서드의 차이는 인자의 처리 방식에 있다. apply는 두번째 인자에서 함수에 전달될 인자들의 배열을 받고 call은 두번째 인자부터 각각 함수에 직접 전달된다.

const person = {
    greet(str1, str2) {
        console.log(this.name + ' says ' + str1 + ' and ' + str2);
    }
}

const person2 = {
    name : 'Hong'
}

person.greet.apply(person2, ['hi', 'hello']);
person.greet.call(person2, 'hi', 'hello');

0개의 댓글