함수 호출 방식과 관계없이 this 를 지정할 수 있음
• call 메서드는 모든 함수에서 사용할 수 있으며, this를 특정값으로 지정할 수 있습니다
• call 을 사용하고 this로 사용할 객체를 넘기면 해당 함수가 주어진 객체의 메서드 처럼 사용
const mike = {
name: "mike"
};
> const tom = {
name: "tom"
};
function showThisName() {
console.log(this.name);
}
showThisName(); -> 아무것도 나오지않음 여기서 this는 window
showThisName.call(mike); -> mike
showThisName.call(tom); -> tom
function update(birthYear, occupation){
this.birthYear = birthYear;
this.occupation = occupation
}
update.call(mike, 1999, "singer") * 첫번째는 this로 사용될 값
두번째 부터는 함수가 사용될 값을 사용
console.log(mike) -> {name : "mike", birthYear: 1999, occupation "singer"}
update.call(tom, 2002, "teacher")
console.log(tom) -> {name : "tom", birthYear: 2002, occupation "teacher"}
• apply는 함수 매개변수를 처리하는 방법을 제외하면 call과 완전히 같습니다.
call은 일반적인 함수와 마찬가지로 매개변수를 직접받지만, apply는 매개변수를 배열로 받습니다.
• apply 는 Array로 받는다
update.apply(mike, [1999, "singer"]) * call과 출력값은 같지만
뒤에 매개변수를 배열로 작성 해야함
console.log(mike) -> {name : "mike", birthYear: 1999, occupation "singer"}
update.apply(tom, [2002, "teacher"])
console.log(tom) -> {name : "tom", birthYear: 2002, occupation "teacher"}
apply는 배열요소를 함수 매개변수로 사용할 때 유용함
const num = [3, 10, 1, 6, 4]
**** apply 사용
const minNum = Math.min.apply(null, nums) *null은 this로 사용될 값
= Math.min.apply(null, [3, 10, 1, 6, 4])
**** call 사용
const maxNum = Math.max.call(null, ...nums)
= Math.max.call(null, 3, 10, 1, 6, 4)
console.log(minNum); -> 1
console.log(maxNum); -> 10
• 함수의 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) ->{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
fn() -> hello,
fn.call(user) -> hello,mike
fn.apply(user) -> hello,mike
let boundFn = fn.bind(user);
boundFn -> hello,mike