*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"
반응형

+ Recent posts