JS 중급 | call, apply, bind

uoah·2023년 1월 25일
0

자바스크립트

목록 보기
28/33
post-thumbnail

🚀 오늘의 학습 목표

  • call
  • apply
  • bind

13.1 call

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

13.1.1 예제 1

const mike = {
  name : 'mike',
};

const tom = {
  name : 'tom',
};

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

showThisName();  //여기에서 this 는 window 를 말한다.
showThisName.call(mike);	//'mike'
showThisName.call(tom);		//'tom'

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

update.call(mike, 1993, 'singer')
console.log(mike); //{name: 'mike', birthYear: 1993, occupation: 'singer'}

update.call(tom, 2001, 'teacher')
console.log(tom); // {name: 'tom', birthYear: 2001, occupation: 'teacher'}

13.1.2 예제 2

최소값과 최대값을 구한다고 하자.

const minNum = Math.min(3, 10, 1, 6, 4);
const maxNum = Math.max(3, 10, 1, 6, 4);

console.log(minNum); // 1
console.log(maxNum); // 10

만약 배열로 만든다면 어떻게 될까?

const minNum = Math.min([3, 10, 1, 6, 4]);
const maxNum = Math.max(3, 10, 1, 6, 4);

console.log(minNum); // NaN
console.log(maxNum); // 10

배열 자체를 넣을 경우 NaN 이 나오기 때문에 이 경우에는 전개구문 (spread syntax) 을 사용한다.

const nums = [3, 10, 1, 6, 4]
const minNum = Math.min(...nums);
const maxNum = Math.max(...nums);

console.log(minNum); // 1
console.log(maxNum); // 10

call 을 사용해 보자.

const nums = [3, 10, 1, 6, 4]

const minNum = Math.min.call(this, ...nums);
// == const minNum = Math.min.call(this, 3, 10, 1, 6, 4);

const maxNum = Math.max.call(this, ...nums);
// == const maxNum = Math.max.call(this, 3, 10, 1, 6, 4);

console.log(minNum); // 1
console.log(maxNum); // 10

13.2 apply

배열 요소를 함수 매개 변수로 사용할 때 유용하다.

매개변수를 처리하는 방법을 제외하면 call 과 같다.
call 은 일반벅인 함수와 마찬가지로 매개변수를 직접 받지만, apply배열(array) 로 받는다.

13.2.1 예제 1

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.apply(mike, [1993, 'singer'])
console.log(mike); //{name: 'mike', birthYear: 1993, occupation: 'singer'}

update.apply(tom, [2001, 'teacher'])
console.log(tom); // {name: 'tom', birthYear: 2001, occupation: 'teacher'}

13.2.2 예제 2

최소값과 최대값을 apply 를 사용하여 구해 보자.

const nums = [3, 10, 1, 6, 4]

const minNum = Math.min.apply(null, nums);
// == const minNum = Math.min(null, [3, 10, 1, 6, 4]);

const maxNum = Math.max.apply(null, nums);
// == const maxNum = Math.max(null, [3, 10, 1, 6, 4]);

console.log(minNum); // 1
console.log(maxNum); // 10

괄호 안의 nullthis 로 사용될 값인데 Math.min 이나 Math 메소드는 this 가 딱히 필요하지 않아 아무 값이나 넣은 것이다.

❗️ 한번 더 짚고 넘어가기

call 과 apply 는 동작 방식은 동일하지만 매개 변수를 받는 방식이 다르다.

call 순서대로 직접 받는다.
apply 배열 형태로 받는다.

13.3 bind

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


const mike = {
  name : 'mike',
};

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

const updateMike = update.bind(mike);

updateMike(1980, 'police');
console.log(mike); //{name: 'mike', birthYear: 1980, occupation: 'police'}

🧑🏻‍💻 예제를 통해 쉽게 이해하기

const user = {
  name : 'mike',
  showName : function (){
    console.log(`hello, ${this.name}`);
  },
};

user.showName();	// hello, mike

let fn = user.showName;

fn();	// hello, 

fn 에 할당할 때 this 를 잃게 되어 name 값인 mike가 나오지 않는다.

call, apply, bind 를 이용해 보자.

Call


fn.call(user);	// hello, mike

apply

fn.apply(user);	// hello, mike

bind

let fnBind = fn.bind(user);	
fnBind(); // hello, mike

0개의 댓글

관련 채용 정보