
call 메서드는 모든 함수에서 사용할 수 있으며, this를 특정값으로 지정할 수 있다.
const mike = {
name: 'Mike';
}
const tom = {
name = 'Tom';
}
function showThisName(){
console.log(this.name);
}
function update(){
this.birthYear = birthYear;
this.occupation = occupation;
}
showThisName.call(mike) // 'Mike'
showThisName.call(tom) // 'Tom'
// 첫번째 인자로 this로 사용될 값을 받는다.
update.call(mike, 1999, 'singer') // {name: 'Mike', birthYear: 1999', occupation: 'singer'}
update.call(tom, 2002, 'teacher') // {name: 'Tom', birthYear: 2002', occupation: 'teacher'}
apply는 함수 매개변수를 처리하는 방법을 제외하면 call과 완전히 같다.
call은 일반적인 함수와 마찬가지로 매개변수를 직접 받지만, apply는 매개변수를 배열로 받는다.
// 위의 call을 apply로 변경하면 아래와 같다.
const mike = {
name: 'Mike';
}
const tom = {
name = 'Tom';
}
function update(){
this.birthYear = birthYear;
this.occupation = occupation;
}
showThisName.call(mike) // 'Mike'
showThisName.call(tom) // 'Tom'
update.call(mike, [1999, 'singer']) // {name: 'Mike', birthYear: 1999', occupation: 'singer'}
update.call(tom, [2002, 'teacher']) // {name: 'Tom', birthYear: 2002', occupation: 'teacher'}
const nums = [3, 10, 1, 6, 4]
const minNum = Math.min(...nums) // 1
const maxNum = Math.max(...nums) // 10
// 이걸 apply로 변경하면
const minNum = Math.min.apply(null, nums) // 1
const maxNum = Math.max.apply(null, nums) // 10
// 이걸 call로 사용한다면
const minNum = Math.min.call(null, ...nums) // 1
const maxNum = Math.max.call(null, ...nums) // 10
함수의 this 값을 영구히 바꿀 수 있다.
const user = {
name: 'ye',
showName: function () {
console.log(`hello, ${this.name}`)
}
}
user.showName() // 'hello, ye'
let fn = user.showName;
fn() // 'hello, ' -> fn에 할당할때 this를 잃어버림.
fn.call(user); // 'hello, ye'
fn.apply(user); // 'hello, ye'
let boundFn = fn.bind(user);
boundFn(); //'hello, ye'