Call & Bind & Apply
함수 안에서 this를 사용하면 Window 객체를 참조하게 된다. 하지만 다른 객체를 참조하길 원할 때 우리는 어떻게 해야할까?
💡 Tip
이 내용을 이해하기 전에, 먼저 this 키워드에 대해 알고 있어야 합니다. 만약 잘모르신다면 아래의 링크를 통해 공부하고 오시는 것을 추천드립니다.
[ JS ] 자바스크립트 this 키워드 정복하기
this 작동 범위let audio = { title: 'a', title2 : this.title, play() { console.log('play this: ', this.title); }};console.log(audio.title2); //undefinedaudio.play(); // play this: a 위 코드에서 함수 블록 스코프 내에 선언되지 않은 th
seio924.tistory.com
Call 사용하기
call()은 함수를 호출하는 함수이다.
// Call();
const fullName = function () {
console.log(this.firstName + " " + this.lastName);
}
const person1 = {
firstName: "John",
lastName: "Doe"
}
// This will return "John Doe"
fullName.call(person1);
코드와 같이 첫 번째 매개변수로 어떠한 것을 전달해주면 호출되는 함수의 this 안에 window 객체가 아닌 전달받은 것을 받게 된다.
var obj = {
string: 'zero',
yell: function() {
alert(this.string);
}
};
var obj2 = {
string: 'what'
};
obj.yell(); // 'zero';
obj.yell.call(obj2); // 'what'
코드 마지막에서 obj.yell.call(obj2)로 this가 가리키는 것을 obj에서 obj2로 바꾸었다. yell은 obj의 메소드임에도 zero 대신에 what이 alert 된 것을 확인할 수 있다.
// Call() with arguments
const fullName = function (city, country) {
console.log(`${this.firstName}, ${this.lastName}, ${city}, ${country}`);
}
const person1 = {
firstName: "John",
lastName: "Doe"
}
fullName.call(person1, "Oslo", "Norway");
또한, 일반 함수처럼 추가적인 인자를 전달하여 사용할 수도 있다.
Apply 사용하기
apply 메서드는 call 메서드와 비슷하지만 인수 부분을 배열로 넣어줘야 한다.
// Apply() with arguments
const fullName = function (city, country) {
console.log(`${this.firstName}, ${this.lastName}, ${city}, ${country}`);
}
const person1 = {
firstName: "John",
lastName: "Doe"
}
fullName.apply(person1, ["Oslo", "Norway"]);
arguments는 모든 함수가 기본적으로 가지고 있는 숨겨진 속성으로, 함수에 전달된 인자들을 배열 형태로 반환한다.
하지만 실제 배열이 아닌 유사 배열이기 때문에, 배열 메서드를 직접 사용할 수 없다. 이때 call과 apply가 빛을 발하게 된다.
function example() {
console.log(arguments);
}
example(1, 'string', true); // [1, 'string', true]
출력 값을 보면 배열 형태인 것을 확인할 수 있다. 하지만 배열 메서드인 join을 사용하려고 하면 문제가 생긴다.
function example2() {
console.log(arguments.join()); // Uncaught TypeError: arguments.join is not a function
}
example2(1, 'string', true);
이렇듯 arguments는 유사 배열을 반환하므로 에러가 발생한다. 하지만 call이나 apply를 사용하면 해결된다.
function example3() {
console.log(Array.prototype.join.call(arguments));
}
example3(1, 'string', true); // '1,string,true'
프로토타입 메서드인 Array.prototype.join()을 호출한 뒤, call()을 사용해 join 함수의 this를 변경할 수 있다.
이때 this를 arguments로 지정하여 join()이 Array 객체 대신 유사 배열인 arguments를 가리키도록 바꾸는 것이다.
이렇게 하면 Array.prototype.join()이 [1, 'string', true].join()처럼 동작하게 되어, arguments에 대해 join 메서드를 사용할 수 있게 된다.
Bind 사용하기
bind 메서드를 이용해서도 함수에서 this가 window 객체 대신 다른 것을 참조하도록 할 수 있다.
bind 메서드가 call, apply와 다른 점은 직접 함수를 실행하지 않고 반환한다는 점이다.
// bind()
function func(language) {
if (language === "kor") {
console.log(`language: ${this.korGreeting}`);
} else {
console.log(`language: ${this.engGreeting}`);
}
}
const greeting = {
korGreeting: "안녕 ",
engGreeting: "Hello ",
};
const boundFunc = func.bind(greeting);
boundFunc('kor');
'Language > JavaScript' 카테고리의 다른 글
[ JS ] 자바스크립트 this 키워드 정복하기 (0) | 2024.10.09 |
---|---|
[ JS ] 자바스크립트 타입 총정리 (0) | 2024.10.09 |
[ JS ] var, let, const ( + 변수 호이스팅 ) (2) | 2024.09.19 |
[ JS ] 이벤트 흐름을 이해해보자 ( Event Bubbling & Capturing ) (0) | 2024.08.29 |