aotoyae

[JS] this 지정 call, apply, bind 본문

JavaScript

[JS] this 지정 call, apply, bind

aotoyae 2023. 12. 14. 20:09

 

 

: 함수 호출 방식과 관계 없이 this를 지정할 수 있다!

 

call : 모든 함수에서 사용할 수 있으며, this를 특정 값으로 지정할 수 있다.

const aoto = {
  name: "aoto",
};
const yae = {
  name: "yae",
};

function showThisName() {
  console.log(this.name);
}

showThisName(); // 빈 값이 반환된다. 여기서 this는 window이기 때문.
showThisName.call(aoto); // "aoto" this => aoto
showThisName.call(yae); // "yae" this => yae

function update(birthYear, ocuupation) {
  this.birthYear = birthYear;
  this.ocuupation = ocuupation;
}

update.call(aoto, 1999, "singer");

console.log(aoto); // {name: 'aoto', birthYear: 1999, ocuupation: 'singer'}

update.call(yae, 2002, "dancer");
console.log(yae);  // {name: 'yae', birthYear: 2002, ocuupation: 'dancer'}

 

apply : 함수 매개변수를 처리하는 방법을 제외하면 call과 완전히 같다.

call은 일반적인 함수와 마찬가지로 매개변수를 직접 받지만, apply는 매개변수를 배열로 받는다.

const aoto = {
  name: "aoto",
};
const yae = {
  name: "yae",
};

function update(birthYear, ocuupation) {
  this.birthYear = birthYear;
  this.ocuupation = ocuupation;
}

update.apply(aoto, [1999, "singer"]);

console.log(aoto); // {name: 'aoto', birthYear: 1999, ocuupation: 'singer'}

update.apply(yae, [2002, "dancer"]);
console.log(yae); // {name: 'yae', birthYear: 2002, ocuupation: 'dancer'}

 

❗️ apply는 배열 요소를 함수 매개변수로 이용할 때 유용하다.

❗️두 번째 매개변수로 배열을 넘겨주면 그 배열을 차례대로 인수로 사용한다.

const minNum = Math.min(3, 10, 1, 6, 4);
// const minNum = Math.min([3, 10, 1, 6, 4]); // NaN
const maxNum = Math.max(3, 10, 1, 6, 4);

console.log(minNum); // 1
console.log(maxNum); // 10

// 2번째 방법
const nums = [3, 10, 1, 6, 4];
const minNum2 = Math.min(...nums);
const maxNum2 = Math.max(...nums);

console.log(minNum2); // 1
console.log(maxNum2); // 10

// apply 사용
// null 은 this를 받는 곳인데 min이나 max는 딱히 this를 필요로 하지 않으니 아무 값이나 넣은 것.
const minNum3 = Math.min.apply(null, nums);
const maxNum3 = Math.max.apply(null, nums);
// = Math.max.apply(null, [3, 10, 1, 6, 4]);

console.log(minNum3); // 1
console.log(maxNum3); // 10

// call 사용, 차례대로 매개변수가 들어가야 하니 스프레드 연산자 사용
const minNum4 = Math.min.call(null, ...nums);
const maxNum4 = Math.max.call(null, ...nums);
//  Math.max.call(null, 3, 10, 1, 6, 4);

console.log(minNum3); // 1
console.log(maxNum3); // 10

 

bind : 함수의 this 값을 영구히 바꿀 수 있다.

const aoto = {
  name: "aoto",
};

function update(birthYear, occupation) {
  this.birthYear = birthYear;
  this.occupation = occupation;
}

const updateAoto = update.bind(aoto); // 이제 이 함수는 항상 aoto를 this로 가진다.

updateAoto(1980, "police");
console.log(aoto); // {name: 'aoto', birthYear: 1980, occupation: 'police'}

 

응용!

const user = {
  name: "aoto",
  showName: function () {
    console.log(`hi, ${this.name}`);
  },
};

user.showName(); // "hi, aoto" .앞에 user가 this

let fn = user.showName;
fn(); // "hi, " => this를 잃어버림, .앞에 아무것도 없어서

fn.call(user); // "hi, aoto"
fn.apply(user); // "hi, aoto"

let boundFn = fn.bind(user);
boundFn(); // "hi, aoto"

 

 

 

🔗 https://youtu.be/KfuyXQLFNW4?si=k8o3MX1lEMjXQZFi