*call, apply, bind:
함수 호출 방식과 관계없이 this 를 지정할 수 있음.
1. call
call메서드는 모든 함수에서 사용할 수 있으며,
this를 특정값으로 지정할 수 있다.
const mike = {
name : "Mike",
};
const tom = {
name : "Tom",
};
function showThisName() {
console.log(this.name);
}
showThisName(); //this = window
showThisName.call(mike); //this = mike
const mike = {
name : "Mike",
};
const tom = {
name : "Tom",
};
function showThisName() {
console.log(this.name);
}
function update(birthYear, occupation) {
this.birthYear = birthYear;
this.occupation = occupation;
}
update.call(mike, 1999, "singer"); //this = mike
console.log(mike);
2. apply
apply는 함수 매개변수를 처리하는 방법을 제외하면 call과 완전히 같다.
call은 일반적인 함수와 마찬가지로 매개변수를 직접 받지만, apply는 매개변수를 배열로 받는다.
const nums = [3, 10, 1, 6, 4];
//나머지 매개변수 사용할 때
const minNum = Math.min(...nums);
const maxNum = Math.max(...nums);
//apply 사용할 때
const minNum = Math.min.apply(null, nums);
// = Math.min.apply(null, [3, 10, 1, 6, 4]) ->null은 this값인데, Math.min이나 Math.max는 this가 필요없어 아무 숫자나 넣은 것
const maxNum = Math.max.call(null, ...nums); ->call은 매개변수를 순서대로 직접 받음.
// = Math.max.call(null, 3, 10, 1, 6, 4)
console.log(minNum);
console.log(maxNum);
3. bind
함수의 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 user = {
name : "Mike",
showName : function () {
console.log(`hello, ${this.name}`);
},
};
user.showName(); //"hello, Mike"
let fn = user.showName;
fn.call(user); //"hello, Mike"
fn.apply(user); //"hello, Mike"
let boundFn = fn.bind(user);
boundFn(); //"hello, Mike"
반응형
'Javascript' 카테고리의 다른 글
자바스크립트 중급 15 - 클래스(Class) (0) | 2023.06.21 |
---|---|
자바스크립트 중급 14 - 상속, 프로토타입(Prototype) (0) | 2023.06.16 |
자바스크립트 중급 12 - setTimeout / setInterval (1) | 2023.06.14 |
자바스크립트 중급 11 - 클로저(Closure) (0) | 2023.06.14 |
자바스크립트 중급 10- 나머지 매개변수, 전개 구문(Rest parameters, Spread syntax) (0) | 2023.06.14 |