this, call(), apply(), 그리고 bind()의 마법
I’m happy to translate the article for you, but I’ll need the full text of the post (the paragraphs, headings, code snippets, etc.) in order to do so. Could you please paste the article’s content here? Once I have it, I’ll provide a Korean translation while keeping the source link, formatting, markdown, and any code blocks exactly as they appear.
안녕하세요, 독자 여러분 👋 – JavaScript 시리즈의 10번째 포스트에 다시 오신 것을 환영합니다
파티에 있다고 상상해 보세요. 누군가 “Hey, 여기 와!” 라고 외칩니다. 누가 대답할까요? 이는 누가 호출했는지와 누구를 바라보고 있는지에 달려 있습니다.
JavaScript에서 this 키워드는 바로 그와 같습니다. 이것은 컨텍스트를 가리키는 특수 식별자로, 현재 함수를 호출하고 있는 객체를 의미합니다.
때때로 this가 가리키는 대상을 제어하고 싶을 때가 있습니다. 바로 그때 마법 같은 삼인조 call(), apply(), 그리고 bind() 가 등장합니다.
Source:
this in JavaScript – The Simple Explanation
this는 현재 함수를 실행하고 있는 객체를 가리키는 키워드입니다.- 이를 “이 함수는 지금 이 객체를 위해 실행되고 있어요.” 라는 비밀 메모라고 생각하면 됩니다.
간단한 규칙: this는 함수를 호출한 주체를 가리킵니다.
this Inside Normal Functions
function showThis() {
console.log(this);
}
showThis(); // In a browser: logs the window object
함수가 전역 컨텍스트에서 호출될 때, this는 window 객체를 가리킵니다.
"use strict";
function showThis() {
console.log(this);
}
showThis(); // undefined
엄격 모드에서는 JavaScript가 전역 객체를 기본값으로 사용하지 않으며, this는 undefined가 됩니다.
Remember: 일반 함수에서
this는 함수가 정의된 위치가 아니라 어떻게 호출되는지에 따라 결정됩니다.
this Inside Objects (Methods)
const person = {
name: "Satya",
greet() {
console.log(`Hello, I’m ${this.name}`);
}
};
person.greet(); // Hello, I’m Satya
함수가 객체의 속성( 메서드 )일 때, this는 그 객체를 가리킵니다.
메서드를 분리하면 어떻게 될까?
const greetFn = person.greet;
greetFn(); // Hello, I’m undefined (or window.name in non‑strict mode)
greetFn은 이제 일반 함수가 되므로 this는 더 이상 person이 아닙니다.
이때 call, apply, bind가 유용해집니다 – 이들은 this 값을 명시적으로 설정할 수 있게 해줍니다.
Source: …
call(), apply(), and bind() – this 제어
call()
- What it does: 지정된
this값과 개별 인수를 사용해 함수를 호출합니다. - Syntax:
functionName.call(thisArg, arg1, arg2, …)
const person1 = { name: "Raj" };
const person2 = { name: "Priya" };
function introduce(city, country) {
console.log(`${this.name} from ${city}, ${country}`);
}
introduce.call(person1, "Delhi", "India"); // Raj from Delhi, India
introduce.call(person2, "Mumbai", "India"); // Priya from Mumbai, India
Real‑life example
const car = {
brand: "Toyota",
getDetails(model) {
console.log(`${this.brand} ${model}`);
}
};
const anotherCar = { brand: "Honda" };
car.getDetails.call(anotherCar, "Civic"); // Honda Civic
car.getDetails를 빌려와서 anotherCar를 this 로 지정해 호출했습니다.
apply()
- What it does:
call()과 동일하지만 인수를 배열(또는 배열 유사 객체) 형태로 전달합니다. - Syntax:
functionName.apply(thisArg, [argsArray])
introduce.apply(person1, ["Delhi", "India"]); // Raj from Delhi, India
introduce.apply(person2, ["Mumbai", "India"]); // Priya from Mumbai, India
When to use apply
- 인수가 이미 배열 형태일 때.
- 가변 개수의 인수를 전달해야 할 때.
const numbers = [10, 20, 30, 40];
console.log(Math.max.apply(null, numbers)); // 40
(여기서는 this 가 의미가 없으므로 null을 전달합니다.)
bind()
- What it does: 함수를 즉시 호출하지 않고,
this가 제공된 값으로 영구히 고정된 새 함수를 반환합니다(선행 인수를 미리 채워 넣을 수도 있습니다). - Syntax:
const boundFn = functionName.bind(thisArg, arg1, arg2, …)
const person = { name: "Satya" };
function greet(greeting) {
console.log(`${greeting}, I’m ${this.name}`);
}
const boundGreet = greet.bind(person, "Hello");
boundGreet(); // Hello, I’m Satya
Real‑life example
const user = {
name: "Amit",
sayHi() {
console.log(`Hi, ${this.name}`);
}
};
// 버튼 클릭 핸들러에 메서드 전달
const sayHiFn = user.sayHi.bind(user);
// 나중에 sayHiFn를 호출해도 `this` 가 여전히 `user` 로 유지됩니다
sayHiFn(); // Hi, Amit
bind 없이 user.sayHi 를 직접 전달하면 this 가 버튼 요소(또는 전역 객체)로 바뀌어 의도한 동작을 하지 못합니다.
빠른 비교 표
| 메서드 | 함수가 호출되는 시점은 언제인가? | 인자는 어떻게 전달되는가? | 일반적인 사용 사례 |
|---|---|---|---|
call() | 즉시 | 개별적으로, 쉼표로 구분 | 인자를 알고 바로 호출하고 싶을 때 |
apply() | 즉시 | 배열(또는 배열 유사 객체) 형태로 | 인자가 이미 배열에 있거나 가변 개수일 때 |
bind() | 나중에 (새 함수를 반환) | 개별적으로(미리 채울 수 있음) | 콜백, 이벤트 핸들러 등에서 고정된 this를 가진 함수가 필요할 때 |
Simple Mnemonics
- C호출 – 쉼표로 구분된 인수.
- A적용 – 인수 배열.
- B바인드 – 나중에 사용할 Borrow & Bind.
주요 요점
this는 항상 함수를 호출하는 사람을 가리킵니다.- 일반 함수(메서드가 아닌)에서는
this가 전역 객체이며(엄격 모드에서는undefined). - 메서드에서는
this가 메서드가 호출된 객체입니다. call()과apply()는 지정된this와 함께 함수를 즉시 호출합니다.bind()는this가 영구히 설정된 새 함수를 반환하며, 나중에 호출할 수 있습니다.- **
call**은 콤마로 구분된 인수를 사용할 때, **apply**는 배열 인수를 사용할 때, **bind**는 고정된 컨텍스트를 가진 재사용 가능한 함수가 필요할 때 사용합니다.
this와 이 세 가지 메서드를 이해하면 많은 버그를 방지하고 함수 실행을 제어하는 슈퍼 파워를 얻을 수 있습니다.
연습 위 예제를 직접 실험해 보면서 JavaScript 컨텍스트에 대한 자신감이 성장하는 모습을 확인하세요! 🚀
곧 자연스럽게 익숙해질 것입니다.
이 블로그가 마음에 드셨길 바랍니다. 오류가 있거나 개선할 점이 있으면 알려 주세요.
LinkedIn과 X에서 저를 찾아보세요 – 거기서 더 많은 내용을 올립니다.