함수 호출 방식과 관계없이 this를 지정할 수 있음
const mike = {
name : "Mike"
}
const tom = {
name : "Tom"
}
function showName() {
console.log(this.name)
}
showName(mike)
// 아무것도 안나옴?
showName.call(mike)
// Mike
function showName() {
console.log(this.name)
}
에서 this가 가르키는 것은 windows이다

그래서 windows.name을 하는 것이고 windows.name은 아무것도 없기 때문에 나오지 않는 것임
call을 붙히게 되면

windows.name이 아니라 call이 const mike를 바인딩하게 되고 this의 범위가 windows에서 const mike로 변하게 되서 windows.name이 아닌 mike.name이 되는 것이다.
const mike = {
name : "Mike"
}
const tom = {
name : "Tom"
}
function update(birthYear, occupation) {
this.birthYear = birthYear
this.occupation = occupation
}
update.call(mike, 1999, "singer")
console.log(mike)
// const mike = {
// name : "Mike"
// birthYear : 1999
// occupation : "singer"
// }
call은 인자로 call(바인딩할 대상, 인자, 인자 ...)로 넘겨줄 수 있다.

함수 매개변수를 처리하는 방법을 제외하면 call하고 완전히 동일함
const mike = {
name : "Mike"
}
const tom = {
name : "Tom"
}
function update(birthYear, occupation) {
this.birthYear = birthYear
this.occupation = occupation
}
update.call(mike, [1999, "singer"])
console.log(mike)
// const mike = {
// name : "Mike"
// birthYear : 1999
// occupation : "singer"
// }
apply는 함수 배열요소 함수 매개변수로 사용할 때 유용함.
const num = [1, 7, 52, 82, 3, 6]
const min = Math.min(num)
// NaN
const min = Math.min(...num)
// 1
const min = Math.min.apply(null, num)
// === Math.min.apply(null, [1, 7, 52, 82, 3, 6])
// 1
const min = Math.min.call(null, ...num)
// === Math.min.call(null, 1, 7, 52, 82, 3, 6)
// 1
Math는 따로 this값을 참조하지 않음
const mike = {
name : "Mike"
}
function update(birthYear, occupation) {
this.birthYear = birthYear
this.occupation = occupation
}
const updateMike = update.bind(mike)
updateMike(1980, "police")
console.log(mike)
// const mike = {
// name : "Mike"
// birthYear : 1980
// occupation : "police"
// }
예시
const user = {
name : "Mike",
showName : function() {
console.log(`hello, ${this.name}`)
}
}
user.showName()
// hello, Mike
let fn = user.showName
// undefined
변수에 할당하면 this 값을 잃어버리게 된다.
// call 사용
fn.call(user)
// hello, Mike
fn.apply(user)
// hello, Mike
let boundFn= fn.bind(user)
boundFn()
// hello, Mike