[JS] call, apply, bind

undefined_potter·2022년 2월 1일
0
post-thumbnail

this 바인딩

const say = () => {
	console.log(this);
}

실행해보면 window 객체가 나타난다. 기본적으로 this 는 window 이기 때문이다. 사실 꼭 window 라고 말할 수 없다.

객체는 전역공간에서의 this, 함수에서의 this, 객체에서의 this, 명시적 bind 시에 따라 다르기 때문이다.

어찌되었든 say 함수에서 window 객체를 사용하고 싶지 않다. this 를 그때 그때 알맞은 객체로 바꿔서 출력하고 싶다. 이것이 this binding 이다.

그리고 명시적으로 위의 this를 window가 아닌 다른 객체로 바꿔주는게 call, apply, bind 함수 이다.

call과 apply

say 함수의 this를 변경하고 싶다면 당연히 this를 대체할 객체가 있어야 한다.

const obj = { name: 'Tom' };
const say = (city) => {
	console.log(`my name is ${this.name}, I live in ${city}`);
}

say.call(obj, "Seoul"); // my name is Tom, I live in Seoul
say.apply(obj, ["Seoul"]); // my name is Tom, I live in Seoul

call 과 apply 는 함수를 호출하는 메서드 이다. 그냥 실행하는게 아니라 첫번째 인자로 this 로 셋팅하고 싶은 객체를 넘겨주어 this를 바꿔 실행한다.

call과 apply의 유일한 차이점은 두번째 인자로 넘겨주는 파라미터의 입력 방식이다. apply는 call과 다르게 두번째 인자로 배열을 넘겨줘야 한다.

bind

const obj = { name: 'Tom' };
const say = (city) => {
	console.log(`my name is ${this.name}, I live in ${city}`);
}

const boundSay = say.bind(obj);
boundSay("Seoul"); // my name is Tom, I live in Seoul

bind 함수가 call, apply 와 다른점은 함수를 실행하지 않는다는 점이다.
대신 새로 바인딩 할 함수 boundSay를 리턴한다. bind 메서드가 호출되면 새로운 함수를 생성한다.

정리

call, apply, bind 메서드는 자바스크립트에서 생성한 함수내에 this를 어느객체로 지정할 것인가를 정하는것이다.

0개의 댓글