this
자바스크립트에서 this 키워드는 함수 호출 방식에 따라 다른 값을 가지는 중요한 개념입니다. 오늘은 this 키워드가 어떻게 동작하는지, 다양한 상황에서 어떻게 달라지는지 자세히 알아보겠습니다.
this 키워드란?
this 키워드는 함수가 호출될 때 결정되는 특별한 객체 참조입니다. this의 값은 함수가 호출된 방식에 따라 달라집니다. 자바스크립트의 유연성과 강력함을 제공하는 동시에, 종종 혼란을 야기하기도 합니다.
전역 컨텍스트에서의 this
전역 컨텍스트에서 this는 전역 객체를 가리킵니다. 브라우저 환경에서는 window 객체를, Node.js 환경에서는 global 객체를 참조합니다.
1
console.log(this); // 브라우저에서는 window, Node.js에서는 global
함수 내부에서의 this
일반 함수 내부에서 호출된 this는 엄격 모드(Strict Mode) 여부에 따라 다릅니다.
비엄격 모드
비엄격 모드에서는 this가 전역 객체를 가리킵니다.
1
2
3
4
5
function regularFunction() {
console.log(this); // window (브라우저 환경)
}
regularFunction();
엄격 모드
엄격 모드에서는 this가 undefined입니다.
1
2
3
4
5
function strictFunction() {
console.log(this); // undefined
}
strictFunction();
메서드 내부에서의 this
객체의 메서드 내부에서 호출된 this는 해당 메서드를 소유하는 객체를 가리킵니다.
1
2
3
4
5
6
7
8
const obj = {
name: 'Alice',
greet: function() {
console.log(this.name); // "Alice"
}
};
obj.greet();
생성자 함수 내부에서의 this
생성자 함수에서 호출된 this는 새로 생성된 객체를 가리킵니다.
1
2
3
4
5
6
function Person(name) {
this.name = name;
}
const person1 = new Person('Bob');
console.log(person1.name); // "Bob"
화살표 함수 내부에서의 this
화살표 함수는 자신만의 this 바인딩을 가지지 않습니다. 대신, 화살표 함수가 정의된 스코프에서 this를 상속받습니다.
1
2
3
4
5
6
7
8
9
10
11
12
const obj = {
name: 'Charlie',
regularFunction: function() {
console.log(this.name); // "Charlie"
},
arrowFunction: () => {
console.log(this.name); // 전역 객체의 name (브라우저에서는 undefined)
}
};
obj.regularFunction();
obj.arrowFunction();
이벤트 핸들러에서의 this
1
2
3
4
5
6
<button id="myButton">Click me</button>
<script>
document.getElementById('myButton').addEventListener('click', function() {
console.log(this); // <button id="myButton">Click me</button>
});
</script>
명시적으로 this 설정하기
call, apply, bind 메서드를 사용하여 명시적으로 this 값을 설정할 수 있습니다.
call 메서드
call 메서드는 함수를 호출하면서 첫 번째 인자로 this 값을 설정합니다.
1
2
3
4
5
6
function greet() {
console.log(this.name);
}
const person = { name: 'Dave' };
greet.call(person); // "Dave"
apply 메서드
apply 메서드는 call 메서드와 유사하지만, 인자를 배열로 받습니다.
1
2
3
4
5
6
function greet(greeting, punctuation) {
console.log(greeting + ', ' + this.name + punctuation);
}
const person = { name: 'Eve' };
greet.apply(person, ['Hello', '!']); // "Hello, Eve!"
bind 메서드
bind 메서드는 새로운 함수를 생성하고, 이 함수의 this 값을 영구히 설정합니다.
1
2
3
4
5
6
7
function greet() {
console.log(this.name);
}
const person = { name: 'Frank' };
const boundGreet = greet.bind(person);
boundGreet(); // "Frank
마무리
자바스크립트의 this 키워드는 함수 호출 방식에 따라 달라지며, 이를 잘 이해하는 것이 중요합니다. 다양한 컨텍스트에서 this가 어떻게 동작하는지 알고 있으면, 코드의 가독성과 유지보수성을 높일 수 있습니다.
