[자바스크립트] call, apply, bind

kim seung chan·2021년 7월 17일
0

call, apply, bind: 함수 호출 방식과 관계 없이 this를 지정할 수 있음

1. call

call: call 메서드는 모든 함수에서 사용할 수 있으며, this를 특정값으로 지정할 수 있습니다.

const mike = {
	name: "Mike",
};

const tom = {
	name: "Tom",
};

function showThisName() {
	console.log(this.name);
}

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

update.call(mike, 1999, "singer"); // mike는 this 의 값 나머지 매겨 변수들은 함수값
undate.call(tom, 2002, "teacher");

2. apply

apply: apply는 함수 매개변수를 처리하는 방법을 제외하면 call과 완전히 같다. call은 일반적인 함수와 마찬가지로 매개변수를 직접 받지만, apply는 매개변수를 배열로 받습니다.

const nums = [3, 10, 1, 6, 4];
const minNum = Math.min(...num);
const maxNum = Math.max(...num); // apply를 사용하고 싶다면 ? 

const minNum = Math.min.apply(null, nums); // 여기서 null은 this 값이다. 

const maxNum = Math.max.call(null, ...nums)

3. bind

함수의 this 값을 영구히 바꿀 수 있습니다.

const mike = {
	name: "Mike",
};

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

const updateMike = update.bind(mike);

undateMike(1980, "police");

0개의 댓글