본문 바로가기
Javascript

javascript this -명백한 바인딩(call, apply, bind) 호출

by reo.l 2021. 1. 16.

마지막으로 명백한 바인딩(call, apply, bind) 호출이다.

call, apply, bind의 메서드는 명시적으로 this를 지정하고 싶을 때 사용한다.

첫 번째 인자가 항상 this값이 된다.

call, apply와 bind는 this 값을 지정한다는 점에서는 같지만 call, apply의 경우는

this의 값을 지정하여 호출하지만 bind는 호출은 하지 않고 this값을 지정하여 함수만 반환한다.

 

call, apply

function printProfile(name, age) {
  return `${this.type} ${name} 나이:${age}`
}

const developer = {
  type: '개발자',
  feature: '언어'
}

const artist = {
  type: '아티스트',
  feature: '노래'
}

console.log(printProfile.call(developer, '김코딩', 30))    // 개발자 김코딩 나이:30
console.log(printProfile.call(artist, 'BTS', 7))         // 아티스트 BTS 나이:7
console.log(printProfile.apply(developer, ['김코딩', 30])) // 개발자 김코딩 나이:30
console.log(printProfile.apply(artist, ['BTS', 7]))      // 아티스트 BTS 나이:7

call은 두 번째 인자로 파라미터를 받지만 apply는 두 번째 인자로 배열을 받는다. 

이점을 빼고는 같다.

 

 

bind

let people1 = {
  name: '유창'
};

let people2 = {
  name: '상래',
  coding: function() {
      console.log(this.name + ' 코딩하자!!');
  }
};

people2.coding(); // 상래 코딩하자!!

let developer = people2.study.bind(people1);
developer(); // 유창 코딩하자!!

bind는 this를 지정하고 함수를 만든다.

bind는 call, apply와 같이 this를 지정하지만 호출하지는 않는다.

그렇기에 함수를 변수에 할당하여 호출하는 형태로 사용해야 한다.

 

 

 

댓글