[JS] call, apply, bind

MiMi·2022년 5월 13일
0

📒JavaScript

목록 보기
2/3
post-thumbnail

타입스크립트를 공부하다가 bind문법이 뭔지 몰라서 공부하게 되었다.

call

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

const mike = {
    name: "Mike",
}

const tom = {
    name : "Tom",
}

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

showThisName(); //여기서 this는 window
showThisName.call(mike); //여기서 this는 객체 mike
showThisName.call(tom); //여기서 this는 객체 tom

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

update.call(mike, 1999, "singer");

console.log(mike); //{ name: "Mike", birthYear: 1999, occupation: "singer" }

apply

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

  • 첫번째 예제
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, [1999, "singer"]);

console.log(mike); //{ name: "Mike", birthYear: 1999, occupation: "singer" }
  • 두번째 예제
const nums = [3, 10, 1, 6, 4];
const minNum = Math.min(...nums); // 1
const maxNum = Math.max(nums); // NaN

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

bind

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

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

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

const updateMike = update.bind(mike); // this의 값을 항상 mike로 받을 수 있음

updateMike(1980, "police")
  • 예제
const user = {
  name: "Mike",
  showName: function () {
    console.log(`heool, ${this.name}`);
  },
};

user.showName(); // hello, Mike

let fn = user.showName;

fn(); // hello, -> this값을 잃어버림
fn.call(user); // hello, Mike
fn.apply(user); // hello, Mike

let boundFn = fn.bind(user);
boundFn(); // hello, Mike

이렇게 call, apply, bind는 함수의 this값을 지정할 수 있다.

profile
이제 막 입문한 코린이 -> 이전중 https://mimi98.tistory.com/

0개의 댓글