웹개발/혼자하는 개발 공부

[자바스크립트] call & bind methods

데브리 2021. 9. 16. 04:28

 

 

 

call()

call을 사용하면 this를 다른 값으로 변경할 수 있음.

 

 

 

 

bind()

this의 값을 바꾸는 것은 비슷하지만, 새로운 function(함수)이 출력된다. 

bind methods allows us to manually set this keywords for any function call.

bind does not immediately call a function, it returns a new function where this keyword is bound. 

 

 

const koreanair = {
  airline: 'Korean Air',
  iataCode: 'KO',
  booking: [],
  book(flightNum, name) {
    console.log(
      `${name} booked a seat on ${this.airline} flight ${this.iataCode}${flightNum}`
    );
    this.bookings.push({flight: `${this.iataCode`}${flightNum}`, name});
  },
};

koreanair.book(239, 'Sally Kim');
koreanair.book(523, 'Jay Park');

 
// aircanada에서 위의 booking method를 쓰고 싶을 때

const aircanada = {
  airline: 'Air Canada',
  iataCode: 'AC',
  bookings: [];
};

const book = koreanair.book;   // This is possible because JavaScript has first class functions.

// book(23, 'Sally Kim');    
koreanair에서 쓰인 booking method를 쓸 수 없음. 
지금 쓰이는 것은 just a regular function call.

// use call method
book.call(aircanada, 23, 'Sally Kim');
console.log(aircanada);
book.call(aircanada, ...flightData);    // used to use Apply method before ES6


// use bind method
const bookAC = book.bind(aircanada);   // will return a new function. this method 필요없음
bookAC(23, 'Jay Park');

const bookAC12 = book.bind(aircanada, 12);
bookAC12('Mark Lee');