1. call
call의 첫 번째 인자는 this 값이 되고, 두 번째 인자부터는 호출하는 함수로 전달된다.
func.call(thisArg[, arg1[, arg2[, ...]]])
2. apply
apply는 매개변수를 배열로 받는다는 점 이외에는 call과 같다.
(Spread 문법으로 apply를 대체할 수 있다.)
func.apply(thisArg, [argsArray])
3. bind
bind는 새로운 함수를 만들고, 함수의 this 값을 영구적으로 바꿀 수 있다. apply, call은 바로 실행되는 반면, bind는 호출이 되면 실행된다.
func.bind(thisArg[, arg1[, arg2[, ...]]])
4. 예제
const obj = {name: 'Tom'};
function foo(city) {
console.log(`I'm ${this.name}, and I live in ${city}`);
}
foo('seoul'); // I'm Tom, and I live in seoul
foo.call(obj, 'seoul'); // I'm Tom, and I live in seoul
foo.apply(obj, ['seoul']); // I'm Tom, and I live in seoul
const obj = {name: 'Tom'};
function foo(city) {
console.log(`I'm ${this.name}, and I live in ${city}`);
}
const boundFoo = foo.bind(obj);
boundFoo('seoul'); // I'm Tom, and I live in seoul.
'TIL 👩🏻💻' 카테고리의 다른 글
TIL : Prototype (0) | 2021.04.10 |
---|---|
TIL : OOP (0) | 2021.04.09 |
TIL : Modern Javascript Koans (0) | 2021.04.08 |
TIL : 짝수생성기 (0) | 2021.04.08 |
TIL : Git workflow (0) | 2021.04.06 |