call / apply
call : 특정 함수가 가리키는 this를 변경시키는 method
- 왜 method인가?
- 그 이유는 함수 자체가 하나의 object이며,
함수의 prototype에 적혀 잇기 때문
- 형태 FUNCTION.call(thisArg, ...argument(FUNCTION의 argument 작성))
ex)
const stu1 = {score : 80,
print : function(name){
console.log(`${name} : ${this.score}`)
}
}
stu1.print('kim') // kim : 80
const stu2 = {score : 90}
stu1.print.call(stu2, 'jung') // jung : 90
또는 const print = stu1.print;
print.call(stu2, 'jung') 도 가능
apply : call과 같으나, 위의 argument를 array로 받는다는 차이점이 있음
const arr = ['jung']
print.apply(stu2, arr);
cf> 하지만, modern js에서는 spread 연산자 때문에 많이 쓰이지는 않음
const arr = ['jung'];
print.apply(stu2, arr) === print.call(stu2, ...arr);
bind : call, apply와 달리 특정 함수의 this를 영구적으로 고정
call, apply와 달리 bind 문이 실행되면 함수를 호출하는 것이 아닌, bind된 함수를 return 함
형태 : FUNCTION.bind(this가 가리킬 값, parameters)
cf> bind를 사용할 때, parameter도 같이 입력하면,
parameter도 고정됨
ex)
const book = function(flightNum, name) ...
const bookEW23 = book.bind(eurowings, 23);
// this가 가리킬 곳은 eurowings 객체, flightNum은 23인 함수 반환
// 실행시킬 때는 bookEW23('ABC');
cf2> eventlistner과 함께 사용
ex)
lufthansa.planes = 300;
lufthansa.buyPlane = function(){
this.planes++;
console.log(this.planes);
}
document.querySelector('.buy').addEventListener(
'click', lufthansa.buyPlane) --- X
? : 위에서 추가한 lufthansa.buyPlane 메소드는
this의 plane를 추가하는 함수이다. 하지만, addEventlistner의 callback 함수가 가리키는 this는 button을 가리키므로,
this.plane은 우리가 의도한 대로의 lufthansa.planes가 추가되는 것이 아닌, button.planes가 추가됨. 따라서 결과가 NaN이 나옴
이를 방지하기 위해서는 bind를 통해 this를 묶어줘야 함(lufthansa.buyPlanes.bind(lufthansa))
cf3> partial application
- bind를 통해 parameter를 미리 지정
ex)
const addTax = (rate, value) =>value + value * rate;
const addVAT = addTax.bind(null, 0.23)
- null로 한 이유는 위 addTax 함수에서 this.--- 등 this를 사용하지 않기 때문
console.log(addVAT(100)); // 123(100+100 * 0.23)
const addTaxRate = function(rate)
return function(value)
return value + value * rate;
const addVAT = addTaxRate(0.23)
console.log(addVAT(100)); // 123
'TIL > JavaScript' 카테고리의 다른 글
| Converting and Checking numbers (0) | 2022.12.16 |
|---|---|
| Closure (0) | 2022.10.05 |
| String Method (0) | 2022.09.02 |
| map, set (0) | 2022.08.28 |
| Class (0) | 2022.07.15 |