TIL024 객체지향프로그래밍: Call & Bind

Somi·2021년 5월 28일
0

JavaScript

목록 보기
20/27
post-thumbnail

1. call()

call()은 실행되는 함수의 this값을 원하는 객체로 바꿔서 실행할 수 있게 해준다.

  • 함수도 객체이며, 모든 함수는 call이라는 메소드를 가지고 있다.
  • 함수.call(객체)라 하면 '함수'라는 객체를 실행시키는 것
  • 여기서 '객체'가 실행되는 함수의 this를 대체한다.
const kim = {
    name: 'kim',
    first: 10,
    second: 20
}

const lee = {
    name: 'lee',
    first: 10,
    second: 10
}

function sum() {
    return this.first + this.second;
}
console.log(sum.call(kim)); //30
console.log(sum.call(lee)); //20

2. bind

bind는 실행되는 함수의 this값을 원하는 객체로 고정시키는 새로운 함수를 만들어낸다.

  • 기존의 함수에는 영향을 주지 않고 새로운 함수를 만들어내는 것이 포인트!
  • this의 값을 영구적으로 바꾸는 함수를 만들어낸다.
const kim = {
    name: 'kim',
    first: 10,
    second: 20
}

const lee = {
    name: 'lee',
    first: 10,
    second: 10
}

function sum() {
    //this = kim
    return this.first + this.second;
}

const kimSum = sum.bind(kim); //this를 kim으로 하는 새로운 함수가 만들어진다.
console.log(kimSum()); //30

0개의 댓글

관련 채용 정보