call,apply,bind

fe_sw·2022년 7월 30일
0

Javascript

목록 보기
4/22
post-thumbnail

this가 함수호출식에 따라 객체를 가르켰다면, call apply bind함수는 직접 this를 지정가능하다.
즉 함수 호출 방식과 상관없이 this를 바인딩 시킬 수 있다.


Call

Call은 this를 바인딩하면서 함수를 호출하는 것이다.
첫번째 인자로 this바인딩할 객체이고 , 두번째 인자는 문자열 매개변수이다.

const obj = {name:"tom"}
const say = function(city){
 console.log(`hello my name is ${this.name} i live in ${city})}
}

say("seoul") //hello my name is , i live in seoul
say.call(obj,"seoul") //hello my name is tom , l live in seoul

Apply

Call은 this를 바인딩하면서 함수를 호출하는 것이다.
첫번째 인자로 this바인딩할 객체이고 , 두번째 인자는 배열 매개변수이다.

const obj = {name:"tom"}
const say = function(city){
 console.log(`hello my name is ${this.name} i live in ${city})}
}

say("seoul") //hello my name is , i live in seoul
say.apply(obj , ["seoul"]) //hello my name is tom , l live in seoul

Bind

Bind는 함수를 호출하는 것이 아닌 , this가 바인딩 된 새로운 함수를 리턴한다.
두번째 인자는 받지 않는다.

const obj = {name:"tom"}
const say = function(city){
 console.log(`hello my name is ${this.name} i live in ${city})}
}

const boundsay = say.bind(obj)
boundsay("seoul") // //hello my name is tom , l live in seoul

0개의 댓글