JavaScript: call, apply, bind?

Sangmin Na·2021년 6월 4일
0

JavaScript

목록 보기
2/7
post-thumbnail

개선을 위한 정보 혹은 틀린 정보가 있다면 자유롭게 코멘트를 작성해주세요 :D

Call, Apply, Bind

👉 Call, Apply, Bind는 Function에서 사용되는 Method들 중 하나이다. Function은 Method가 없는지 알았는데 어떻게 존재하지? 이런 질문을 던질 수 있을 것이다. 이에 대한 답변은 바로 Function도 Object들 중 하나이기 때문에 Method가 존재한다.

👉 위 메소드들을 이해하는데 this에 대한 개념을 잘 알고 있어야 쉽다.

Call, Apply

👉 설명을 먼저 하는 것 보다 예시를 드는게 이해가 가장 빠르다.

const greeting = function(a, b){
	console.log(`Hello, You can call me ${this.name}. I am interestend 
    	in ${a} and ${b}}`)
}

const person1 = {name: 'James'}
const person2 = {name: 'Tom'}
const person3 = {name: 'Lee'}

greeting('Music', 'Movie') ;
// Hello, You can call me . I am interestend in Music and Movie

greeting.call(person2 ,'Music', 'Movie');
// Hello, You can call me Tom. I am interestend in Music and Movie

greeting.apply(person3 ,['Music', 'Movie']);
// Hello, You can call me Lee. I am interestend in Music and Movie

✔️ greeting 함수를 보면 a, b 두 인수를 받아 함수를 실행하는 것을 알 수 있다. 그런데 자세히 보면 this.name 이라는 this keyword를 사용한 변수가 있다는것 을 확인 할 수 있다.

✔️ this keyword는 Object에서 사용되었다. 그러므로 call, apply 혹은 bind에서 첫 번째 인수로 사용 될 변수는 Object로 이루어져 있어야 한다.

// Objects
const person1 = {name: 'James'}
const person2 = {name: 'Tom'}
const person3 = {name: 'Lee'}


👉 본격적으로 call, apply Method을 분석해보자.

greeting('Music', 'Movie') ;
// Hello, You can call me . I am interestend in Music and Movie

greeting.call(person2 ,'Music', 'Movie');
// Hello, You can call me Tom. I am interestend in Music and Movie

greeting.apply(person3 ,['Music', 'Movie']);
// Hello, You can call me Lee. I am interestend in Music and Movie


✔️ 첫 번째 호출한 함수는 Method를 사용하지 않아 this.name을 출력하지 못하였다.
✔️ 두 번째 호출한 함수는 call Method을 사용하였다. 첫 번째 인수(Parameter)로 Object(perosn2)을 받고 두 번째, 세 번째는 함수에게 인자(Argument)를 전달하였다.
✔️ 세 번째 호출한 함수는 apply Method을 사용하였다. 첫 번째 인수도 마찬가지로 Object(person3)를 인자로 사용하였다. 그러나 두 번째 인자는 Array로 받아 사용하였다.

💡 call, apply는 Method는 각자의 Object(Method의 첫 번째 인수)에 접근하여 this.name의 value를 return한다. call과 apply의 차이점은 apply는 Array을 사용하여 함수에게 인자를 전달한다는 점이다.

Bind

👉 Bind란 단어를 직역하면 묶다라는 뜻이 있다. 그대로 받아들이면 이해하기 쉽다. Function과 Object의 this keyword을 묶는다고 생각하면 된다.

const greeting = function(a, b){
	console.log(`Hello, You can call me ${this.name}. I am interestend 
    	in ${a} and ${b}}`)
}

const person1 = {name: 'James'}

const greetingJames = greeting.bind(person1);

greetingJames('music', 'movie')
// Hello, You can call me James. I am interestend in Music and Movie

✔️ bind는 call, apply method처럼 this keyword를 연결해준다.
✔️ bind는 call, apply와 다르게 함수를 바로 출력하지 않는다.
✔️ greetingJames Variable(변수)에 Bind(묶어)두어 사용한다.


Which One To Use?

👉 Call, Bind를 사용하면 된다.
👉 Apply는 잘 사용되지 않는 메소드이다.


Reference

0개의 댓글