call, apply, bind의 차이점

tk_jang·2022년 6월 20일

자바스크립트

목록 보기
6/7
post-thumbnail

call과 apply

call과 apply는 함수를 호출하는 함수이다.
그러나 그냥 실행하는 것이 아니라
첫 번째 인자에 this로 setting하고 싶은 객체를 넘겨주어
this를 바꾸고나서 실행한다.

호출 방법

const names  = {name:'경태'};

const intro = function(city){
	console.log(`안녕 난 ${this.name}야 난 ${city} 살아`)
}

intro("경기도")  // 안녕 난 야 경기도 살아
intro.call(names, "경기도") // 안녕 난 경태야 난 경기도 살아
intro.apply(names, ["경기도"]) // 안녕 난 경태야 난 경기도 살아

call 과 apply 의 사용법 위와 같은 방법으로 호출 하고 사용한다.

bind

const names = {name:"경태"}

const intro = function(city){
	console.log(`안녕 난 ${this.name}(이)야 난 ${city}살아`)
}

const introduce = intro.bind(names);
introduce("경기")

bind함수가 call, apply와 다른 점은 함수를 실행하지 않는다는 점이다. 대신 bound함수를 리턴한다. 이 bound함수(boundSay)는 이제부터 this를 obj로 갖고 있기 때문에 나중에 사용해도 된다. bind에 사용하는 나머지 rest 파라미터는 call과 apply와 동일하다.

0개의 댓글