자바스크립트에서는 일방적인 방법 외에도 함수를 어디서 어떻게 호출했느냐에 관계없이 this가 무엇인지
지정할 수 있습니다.
그럼 여기서 this는 정확히 뭔데?라는 의문이 들 수 있습니다.
이번 글에서는 this에 대해 알아보겠습니다.
call
call()메소드는 모든 함수에서 사용할 수 있으며, this를 특정값으로 지정할 수 있습니다.
const mike = {
name : "Mike",
}
const tom={
name:"Tom",
}
function showThisName(){
console.log(this.name);
}
showThisName(); // 아무런 값이 뜨지 않음
showThisName.call(mike); //"Mike"
그냥 showThisName();을 호출하면 아무런 값이 뜨지 않습니다. 왜나하면 여기서 this는
window를 가르키기 때문입니다.
반면 showThisName().call(mike);는 mike를 전달해주면서 Mike가 나오게 됩니다.
함수를 호출하면서 call을 사용하고 this로 사용할 객체를 넘기면 해당 함수가 주어진 객체의 메소드인 것처럼
사용할 수 있습니다.
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);
update.call(tom,2002,"teacher");
console.log(tom);
위의 코드처럼 객체에 새로운 속성과 값을 추가할수있습니다.
call의 첫번째 매개변수는 this로 사용할 값이고
매개변수가 더있으면 그 매개변수는 함수로 전달되어집니다.
apply
apply는 call과 매개변수를 처리하는 방식만 빼면 동일합니다.
call은 매개변수를 직접 받지만, apply는 배열 형태로 매개변수를 받습니다.
const mike = {
name : "Mike",
}
const tom={
name:"Tom",
}
function update(birthYear, occupation){
this.birthYear=birthYear;
this.occupation=occupation;
}
update.apply(mike,[1999,"singer"]);
console.log(mike);
update.apply(tom,[2002,"teacher"]);
console.log(tom);
위의 코드에서 볼 수 있듯이 매개변수로 배열을 전달합니다.
apply의 앞의 a와 array의 a를 묶어서 이해하면 더 쉽게 암기할 수 있습니다.
아래와 같은 상황에서도 apply를 사용할 수 있습니다.
const nums = [3,10,1,6,4];
//const minNum=Math.min(...nums);
const minNum=Math.min.apply(null,nums);
console.log(minNum); // 1
bind
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);
// {name: "Mike", birthYear: "1980", occupation: "police"}
update함수를 이리저리 옮기면서 호출하면 this값을 "Mike"로 나오게 하려면 bind를 사용하면 됩니다.
const updateMike = update.bind(mike); 이 함수는 항상 mike를 this로 받습니다.
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
const boundFn = fn.bind(user);
boundFn(); // hello, Mike
fn();을 호출하면 아무값도 나오지 않습니다.fn();을 할당할 때 this를 잃어버리게 되는것입니다.
메소드는 .앞에 있는게 this입니다.
호출할 때 fn()만 호출하니까 this가 없는 것입니다. 이럴 때에는 call을 사용하면 fn.call(user); this로 사용할 값 user를 넣어주면 됩니다.
'프론트엔드 > javascript' 카테고리의 다른 글
자바스크립트 - 클래스(Class) (0) | 2023.04.10 |
---|---|
자바스크립트 - 상속,프로토타입(Prototype) (0) | 2023.04.10 |
자바스크립트 - setTimeout/setInterval (0) | 2023.04.09 |
자바스크립트 클로저(Closure) (0) | 2023.04.09 |
자바스크립트 - 나머지 매개변수, 전개구문(Rest parameters, Spread syntax) (0) | 2023.04.09 |