본문 바로가기

개발/JavaScript

[JS] call, apply, bind 함수

 

call, apply, bind

- this를 사용하는 함수

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

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

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

showThisName(); // 아무것도 찍히지 않음
// call(): this로 사용할 매개변수
showThisName.call(mimi);
showThisName.call(toto);

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

// apply(): 매개변수를 배열로 보냄
update.apply(mimi, [1999, "singer"]);
console.log(mimi);
update.apply(toto, [2020, "dancer"]);
console.log(toto);

const nums = [3, 19, 1, 5, 6];
// const minNum = Math.min(...nums);
// const maxNum = Math.max(...nums);

const minNum = Math.min.apply(null, nums); // null: this로 사용할 값 -> Math는 this가 필요 없어서 null 사용
const maxNum = Math.max.call(null, ...nums); // call()은 배열이 아닌 매개변수를 사용해야하기 때문에 spread 연산자 사용

console.log(minNum);
console.log(maxNum);

// bind(): 함수의 this 값을 지정
const updateMimi = update.bind(mimi); // 항상 mimi를 this로 받음
updateMimi(1997, "rapper"); // mimi를 생략
console.log(mimi);

 

'개발 > JavaScript' 카테고리의 다른 글

[NestJS] Project setup, 구조  (0) 2022.08.10
[JS] Promise, async, await  (0) 2022.08.09
[JS] Object Methods  (0) 2022.08.08
[TS] 블록체인 만들기  (0) 2022.08.07
[TS] declaration file, JSDoc  (0) 2022.08.07