call, apply, bind

김세주·2021년 1월 20일
0

JavaScript

목록 보기
7/12
let kim = {name:'kim', first:10, second:20}
let lee = {name:'lee', first:10, second:10}

function sum() {
    return this.first + this.second
}

여기서 sumthis 는 아무도 가르키지 않는다.
그래서 this 가 누군가를 가르켜야 한다.

call의 사용
sum.call() === sum()
모든 함수는 call 이라는 메서드를 가지고있다.
자바스크립트에서는 함수도 객체이기때문.

sum.call(kim) === 30 kim이 this가 된다.

예를 들어 sum에 인자가 있다면,

let kim = {name:'kim', first:10, second:20}
let lee = {name:'lee', first:10, second:10}

function sum(prefix) {
    return prefix + (this.first + this.second)
}

sum.call(lee, ' => ')

이렇게 call을 사용시 첫번째인자는 this가 되고 그 다음 인자부터는 sum의 파라미터가 된다.

apply

비슷한데 다음인자를 배열로 받는다.

bind

어떤 함수의 내부적인 this의 값을 영구적으로 바꾸는 새로운 함수를 만들어 낸다.
기존 함수에 영향 x

let kim = {name:'kim', first:10, second:20}
let lee = {name:'lee', first:10, second:10}

function sum(prefix) {
    return prefix + (this.first + this.second)
}

let bindSum = sum.bind(kim, '->')
console.log(bindSum())

call은 실행할때 함수의 context (this)의 값을 바꾼다.
bind는 어떤 함수의 this의 값을 영구적으로 바꾸는 새로운 함수를 만든다.

bind 묶는다 this를 고정시킨다. 그 함수 내부적으로 this를 뭘로 쓸거냐? kim으로 쓸거다

call은 실행되는 함수의 this값을 원하는 객체로 바꿔서 실행할 수 있게 해준다.
bind는 실행되는 함수의 this값을 원하는 객체로 고정시키는 새로운 함수를 만들어낸다.

profile
시간은 내 편이다.

0개의 댓글