자바스크립트를 배운 지 얼마 안 된 개발자들이 가장 헷갈려하는 개념이 뭘까? 단연 this 바인딩이다. 같은 함수인데도 어떻게 호출되는지에 따라 this가 가리키는 객체가 완전히 달라진다. 콘솔에 찍어보니 undefined가 나왔고, 어느 순간엔 window 객체가 나왔고, 또 다른 상황에선 의도한 객체가 나온다. 혼란스럽다. 다만 대부분의 개발자들은 this의 정확한 작동 원리를 모르고 인터넷에서 주워온 코드를 복사해 붙이거나, 무작정 화살표 함수로 바꿔본다. 이번에는 this가 정확히 뭔지, 어떤 상황에서 어떻게 바뀌는지, 어떻게 명시적으로 고정할 수 있는지 완벽하게 정리해서 소개하겠다.
this는 자바스크립트에서 현재 코드가 실행되고 있는 주인(객체)을 가리키는 키워드다. 중요한 점은 this가 함수를 정의할 때 결정되는 게 아니라, 함수를 어떻게 호출하는가에 따라 실행 시점에 결정된다는 것이다.
예를 들어보자. 같은 함수라도 호출 방식에 따라 this가 달라진다.
function greet() {
console.log(this.name);
}
const person = { name: '철수', greet: greet };
greet(); // this = window(또는 undefined in strict mode)
person.greet(); // this = person 객체
같은 greet 함수인데 호출 방식이 다르니까 this가 다르다. 첫 번째는 그냥 함수를 호출했고, 두 번째는 person 객체의 메서드로 호출했다. 이게 핵심이다.
this가 결정되는 방식은 크게 4가지로 나뉜다.
| 바인딩 규칙 | 호출 형식 | this 값 | 예시 |
|---|---|---|---|
| 기본 바인딩(Default) | 일반 함수 호출 | window(또는 undefined) | func() |
| 암묵적 바인딩(Implicit) | 메서드 호출 | 메서드를 소유한 객체 | obj.func() |
| 명시적 바인딩(Explicit) | call/apply/bind 사용 | 전달된 첫 인자 객체 | func.call(obj) |
| new 바인딩 | 생성자 함수 호출 | 새로 만든 인스턴스 | new Func() |
함수를 단순히 호출하면 this는 전역 객체를 가리킨다. 브라우저 환경에선 window, Node.js 환경에선 global이다. strict mode에선 undefined가 된다.
// ✗ 기본 바인딩 오류 사례
function showName() {
console.log(this.name); // this = window
}
const myName = 'Alice';
showName(); // undefined(전역 변수는 this와 무관)
// ✓ strict mode에서 에러 감지
'use strict';
function showName() {
console.log(this.name); // TypeError: Cannot read property 'name' of undefined
}
showName();
객체의 메서드로 함수를 호출하면 this는 그 객체를 가리킨다. 콜 체인을 따라 호출한 객체만 중요하다.
// ✓ 올바른 메서드 호출
const user = {
name: '철수',
greet() {
console.log(this.name);
}
};
user.greet(); // '철수' 출력
// ✗ 메서드 분리로 인한 바인딩 손실
const method = user.greet;
method(); // undefined 출력(this = window)
// ✓ 고차 함수 콜백에서 메서드 넘길 때 주의
const user2 = {
name: '영희',
greet() { console.log(this.name); },
executeCallback(callback) {
callback(); // this 손실
}
};
user2.executeCallback(user2.greet); // undefined
call, apply, bind 메서드로 this를 강제로 지정할 수 있다.
// ✓ call()로 this 명시
function introduce(age, city) {
console.log(this.name + ', ' + age + '살, ' + city);
}
const person1 = { name: '철수' };
const person2 = { name: '영희' };
introduce.call(person1, 30, '서울'); // 철수, 30살, 서울
introduce.call(person2, 25, '부산'); // 영희, 25살, 부산
// ✓ apply()는 배열 형태로 인자 전달
introduce.apply(person1, [30, '서울']); // 철수, 30살, 서울
// ✓ bind()는 새로운 함수를 반환(즉시 실행 아님)
const boundIntroduce = introduce.bind(person1, 30);
boundIntroduce('서울'); // 철수, 30살, 서울
new 키워드로 함수를 호출하면 새로운 객체가 생성되고, this는 그 인스턴스를 가리킨다.
// ✓ 생성자 함수
function Person(name, age) {
this.name = name;
this.age = age;
}
const john = new Person('John', 30);
console.log(john.name); // 'John'
console.log(john instanceof Person); // true
// ✗ new 없이 호출하면 this가 전역 객체가 됨
const notAnInstance = Person('Jane', 25); // this = window
console.log(typeof notAnInstance); // 'undefined'
console.log(window.name); // 'Jane' (전역 오염)
화살표 함수는 일반 함수와 완전히 다르게 작동한다. 화살표 함수는 this를 갖지 않는다. 대신 상위 스코프의 this를 그대로 사용한다(렉시컬 this 바인딩).
// ✗ 일반 함수에서 콜백 내 this 손실
const user = {
name: '철수',
hobbies: ['독서', '영화'],
printHobbies() {
this.hobbies.forEach(function(hobby) {
console.log(this.name + '은(는) ' + hobby + '을(를) 좋아한다'); // this = undefined
});
}
};
user.printHobbies(); // undefined은(는) 독서을(를) 좋아한다...
// ✓ 화살표 함수는 상위 this를 유지
const user2 = {
name: '영희',
hobbies: ['독서', '영화'],
printHobbies() {
this.hobbies.forEach((hobby) => {
console.log(this.name + '은(는) ' + hobby + '을(를) 좋아한다'); // this = user2
});
}
};
user2.printHobbies(); // 영희은(는) 독서을(를) 좋아한다
주의: 화살표 함수는 call, apply, bind로 this를 변경할 수 없다. 렉시컬 this가 고정되어 있기 때문이다.
// ✗ 화살표 함수는 this 변경 불가
const obj1 = { name: '철수' };
const obj2 = { name: '영희' };
const arrowFunc = () => console.log(this.name);
arrowFunc.call(obj1); // window.name 출력(this 변경 무시됨)
// ✗ 메서드 분리로 인한 this 손실
const button = {
label: '클릭하세요',
onClick() {
console.log(this.label);
}
};
document.getElementById('btn').addEventListener('click', button.onClick);
// 클릭하면 undefined 출력(this = button 아닌 DOM 요소)
// ✓ bind로 this 고정
document.getElementById('btn').addEventListener('click', button.onClick.bind(button));
// 클릭하면 '클릭하세요' 출력
// ✓ 화살표 함수로 렉시컬 this 사용
const button2 = {
label: '클릭하세요',
onClick() {
document.getElementById('btn').addEventListener('click', () => {
console.log(this.label); // this = button2
});
}
};
button2.onClick();
// ✗ setTimeout에서 this 손실
const counter = {
count: 0,
increment() {
setTimeout(function() {
this.count++; // this = window
console.log(this.count); // NaN
}, 1000);
}
};
counter.increment();
// ✓ 화살표 함수로 해결
const counter2 = {
count: 0,
increment() {
setTimeout(() => {
this.count++; // this = counter2
console.log(this.count); // 1
}, 1000);
}
};
counter2.increment();
// ✓ bind로도 가능
const counter3 = {
count: 0,
increment() {
setTimeout(function() {
this.count++;
console.log(this.count);
}.bind(this), 1000);
}
};
counter3.increment();
// ✗ 메서드 분리 시 this 손실
class User {
constructor(name) {
this.name = name;
}
greet() {
console.log(this.name);
}
}
const user = new User('철수');
const greetFunc = user.greet;
greetFunc(); // undefined
// ✓ bind로 고정
const greetFunc2 = user.greet.bind(user);
greetFunc2(); // '철수'
// ✓ 클래스 필드로 화살표 함수 사용
class User2 {
constructor(name) {
this.name = name;
}
greet = () => {
console.log(this.name);
}
}
const user2 = new User2('영희');
const greetFunc3 = user2.greet;
greetFunc3(); // '영희'
여러 규칙이 중첩될 때는 다음 우선순위를 따른다.
1. new 바인딩 > 2. 명시적 바인딩(call/apply/bind) > 3. 암묵적 바인딩(메서드) > 4. 기본 바인딩
화살표 함수는 위 규칙 모두를 무시하고 렉시컬 this를 사용한다.
// 우선순위 비교
const obj = { value: 'obj' };
function getValue() {
return this.value;
}
const boundGetValue = getValue.bind({ value: 'bound' });
console.log(getValue.call(obj)); // 'obj' (명시적 > 기본)
console.log(boundGetValue.call(obj)); // 'bound' (한 번 bind되면 call도 무시)
console.log(new boundGetValue()); // 새 인스턴스(new > bind, value 없음)
this는 자바스크립트의 가장 헷갈리는 개념이지만, 호출 방식에 따라 결정된다는 원칙 하나만 명확히 하면 모든 게 풀린다. 함수를 그냥 호출하는지, 메서드로 호출하는지, call/bind로 명시하는지, new로 생성자 호출하는지를 먼저 판단하면 this가 무엇인지 자동으로 나온다. 화살표 함수는 이 모든 규칙을 무시하고 상위 스코프의 this를 쓴다는 점만 기억하자. 이 글의 4가지 규칙과 실전 사례를 참고해서 콘솔에서 직접 하나씩 실행해본다면, 앞으로 this 오류로 인한 undefined 지옥에서 벗어날 수 있을 것이다.