JavaScript

[JavaScript] call, apply, bind

반응형

1. call

아래 코드를 실행시켜보면 this.name 에는 아무것도 나오지 않습니다.

const mike = {
  name: "Mike"
}

const tom = {
  name: "Tom"
}

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

showThisName();

 

이 때 call() 을 사용해서 this가 무엇인지 정의해줄 수 있습니다.

showThisName.call(mike);

 

showThisName에 call로 mike라는 객체를 받으면 this는 mike를 가리키게 됩니다. 따라서 this.name은 Mike가 출력되겠죠.

 

call로 업데이트해 줄 객체를 지정해서 값을 바꿀 수도 있습니다.

const mike = {
  name: "Mike"
}

const tom = {
  name: "Tom"
}

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

update.call(mike, 1990, 'developer')

console.log(mike)

 

 

2. apply

위에서 작성했던 코드를 aplly() 로 다음처럼 바꿀 수 있습니다.

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, [1990, 'developer'])

console.log(mike)

차이가 보이시나요?

 

mike라는 객체 다음 인자 즉, update함수의 인자를 배열로 묶어서 넘겨줍니다.

 

apply는 배열을 인자로 받는 경우 효과적으로 사용할 수 있습니다.

 

조금 더 알아보겠습니다.

const nums = [3, 10, 1, 6, 8];

const minNum = Math.min(nums);
const maxNum = Math.max(nums);

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

위 코드를 출력하게 되면 minNum, maxNum 모두 NaN이 출력됩니다.

 

배열인자를 풀어써줘야합니다. spread syntax를 써보겠습니다.

 

const nums = [3, 10, 1, 6, 8];

const minNum = Math.min(...nums);
const maxNum = Math.max(...nums);

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

 

이제 apply() 를 사용해 보겠습니다.

 

apply는 두번째 매개변수로 배열을 받으면 그 배열을 차례대로 인식합니다.

 

 

const nums = [3, 10, 1, 6, 8];

// const minNum = Math.min(...nums);
// const maxNum = Math.max(...nums);

const minNum = Math.min.apply(null, nums)
const maxNum = Math.max.apply(null, nums)

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

다음처럼 call()도 사용해 볼 수 있습니다.

const nums = [3, 10, 1, 6, 8];

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

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

 

call() 과 apply()는 동작방법은 같고 인자를 받는 방법만 다릅니다.

 

 

3. bind

bind() 함수의 this값을 영구적으로 바꿀 수 있습니다. 다음과 같이 사용합니다.

 

const mike = {
  name: "Mike",
}

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

const updateMike = update.bind(mike);

updateMike(1990, "police");
console.log(mike)

 

실제 사용 예제입니다.

const user = {
  name: "Mike",
  showNmae: function () {
    console.log(`hello, ${this.name}`);
  }
}

user.showNmae();

let fn = user.showNmae;

fn.call(user);
fn.apply(user);

let boundFn = fn.bind(user);

boundFn();

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

반응형