call, apply, bind

Goody·2021년 2월 3일
0

자바스크립트

목록 보기
6/13

들어가며

JS에서는 함수를 어디서 어떻게 호출하느냐와 관계없이this 가 무엇을 가리키는지 지정할 수 있다. call, apply , bind 를 이용하면 된다.



call

모든 함수에서 사용할 수 있으며, this 를 특정 값으로 지정할 수 있다.

const bruce = { name: "Bruce"};
const madeline = { name: "Madeline"};

// 이 함수는 어떤 객체에도 연결되지 않았지만 this 를 사용한다.
function greet() {
    return `Hello, I'm ${this.name}!`;
}

greet();			// "Hello, I'm undefined!"
greet.call(bruce);	// "Hello, I'm bruce!""
greet.call(madeline); // "Hello, I'm madeline!"

call() 의 첫 번째 매개변수는 this로 사용할 값이고, 매개변수가 더 있으면 호출하는 함수로 전달된다.

const bruce = { name: "Bruce"};
const madeline = { name: "Madeline"};

function update(birthYear, occupation) {
	this.birthYear = birthYear;
	this.occupation = occupation;
}

update.call(bruce, 1949, 'singer');
update.call(Madeline, 1942, 'actress');



apply

call() 과 비슷하나, 호출하는 함수로 전달하는 매개변수들을 배열로 받는다.

const bruce = { name: "Bruce"};
const madeline = { name: "Madeline"};

function update(birthYear, occupation) {
	this.birthYear = birthYear;
	this.occupation = occupation;
}

update.apply(bruce, [1949, 'singer']);
update.apply(Madeline, [1942, 'actress']);



bind

this 의 값을 영구적으로 바꿀 수 있다.

  • 하나의 메서드를 이리저리 옮기면서도, 호출할 때 메서드 내 this 가 항상 지정한 객체만을 가리키게끔 할 때 사용한다.
const bruce = { name: "Bruce"};
const madeline = { name: "Madeline"};

function update(birthYear, occupation) {
	this.birthYear = birthYear;
	this.occupation = occupation;
}

const updateBruce = update.bind(bruce);	// updateBruce는 이제 항상 bruce만 수정한다.

updateBruce(1904, "actor");
updateBruce.call(Madeline, 1274, "king");

/* bruce = {
	name : "Bruce",
    birthYear : 1274,
    occupation : "king"
} */

bind 는 call, apply 와 함께 사용할 수 없는 거나 마찬가지이다.

  • bind 에 매개변수를 넘기면 항상 그 매개변수를 받으면서 호출되는 새 함수를 만들 수 있다.
const updateBruce1949 = update.bind(bruce, 1949);
updateBruce1949("singer, songwriter");

/* bruce = {
	name : "Bruce",
	birthYear : 1949,
	occupation : "singer, songwirter";
} */
  • bind 는 함수를 반환한다. (커링)

REFERENCE

러닝 자바스크립트 (이선 브라운 저)

0개의 댓글