// 함수 호출 방식과 관계 없이 this 를 지정할 수 있다.
call
call 메서드는 모든 함수에서 사용할 수 있으며, this를 특정값으로 지정할 수 있다.
const mike = {
name: "Mike",
}
const tom = {
name: "Tom",
}
function showThisName() {
console.log(this.name);
}
showThisName(); // 여기서 this 는 window 를 가리키기 때문에 "" 가 나온다. 공백
showThisName.call(mike); // Mike. this 가 mike 를 가리키게 된다.
showThisName.call(tom); // Tom
function update(birthYear, occupation) {
this.birthYear = birthYear;
this.occupation= occupation;
}
update.call(mike, 1993, "teacher"); // 첫번째 인자로 this 로 사용 할 mike, 다음부터는 매개변수
console.log(mike); // {name: "Mike", birthYear: 1993, occupation: "teacher"}
====================================================
let nums = [10, 7, 30, 4, 72];
const minNum = Math.min.call(null, ...nums);
console.log(minNum); // 4
apply
apply 는 함수 매개변수를 처리하는 방법을 제외하면 call 과 똑같다.
call 은 일반적인 함수와 마찬가지로 매개변수를 직접 받지만, apply 는 배열로 받는다.
update.apply(mike, [1993, "teacher"]);
console.log(mike);
update.apply(tom, [2001, "doctor"]);
console.log(tom);
====================================================
let nums = [10, 7, 30, 4, 72];
const minNum = Math.min.apply(null, nums);
console.log(minNum);
bind
함수의 this 값을 영구히 바꿀 수 있다.
const mike = {
name: "Mike",
};
function update(birthYear, age) {
this.birthYear = birthYear;
this.age = age;
}
const updateMike = update.bind(mike);
updateMike(198, "police");
console.log(mike); // {name: "Mike", birthYear: 198, age: "police"}
updateMike(198, "nurse");
console.log(mike); // {name: "Mike", birthYear: 198, age: "nurse"}
//updateMike의 this는 영구적으로 mike 를 가리키게 되었다.
====================================================
const user = {
name: "Malza",
showName: function () {
console.log(`hello, ${this.name}`);
},
};
user.showName(); // hello, malza
let func = user.showName; // 함수만 func 에 넣어보자.
func(); // this 를 잃었다. hello, 라고 출력된다.
func.call(user); // 제대로 출력된다. hello, malza
func.apply(user); // 제대로 출력된다.
let boundFn = func.bind(user); // 영구히 user 를 this로 가진다.
boundFn(); // 제대로 출력된다.