일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 | 29 |
30 | 31 |
- docker
- Linux
- PostgreSQL
- MongoDB
- 오블완
- 트랜잭션
- 자바
- Javascript
- IntelliJ
- 리눅스
- github
- java
- analytics4
- 추상클래스
- pandas
- spring
- JPA
- rsync
- SQL
- 티스토리챌린지
- MariaDB
- 명령어
- Python
- oracle
- git
- 호이스팅
- mysql
- group by
- mssql
- DBMS
- Today
- Total
hanker
JavaScript - this 키워드 (현재 실행 중인 환경에 따라 다른 객체를 참조) 본문
이번 글에서는 JavaScript에서 가장 많이 헷갈리는 개념 중 하나인 this 키워드에 대해서 알아보자.
this는 실행 컨텍스트에 따라 다르게 동작하기 때문에 올바르게 이해하는 것이 중요하다!
1. this 란?
this 는 현재 실행 중인 컨텍스트에 따라 다른 객체를 참조하는 키워드이다.
즉, this 가 가리키는 대상은 코드가 실행되는 방식에 따라 달라진다.
2. this의 동작
- 기본적으로 전역 객체를 참조
- 객체의 메서드 내부에서는 해당 객체를 참조
- 화살표 함수에서는 부모 컨텍스트의 this를 상속
- 생성자 함수에서는 새로 생성된 객체를 참조
- call, apply, bind를 사용하면 this를 명시적으로 변경 가능
여기까지 정의를 알아보고 아래 코드에서 자세하게 알아보자.
2-1. 전역 공간에서의 this
console.log(this);
// 브라우저에서는 'window'
// Node.js에서는 'global'
// 함수 내부에서의 this
function showThis() {
console.log(this);
}
showThis();
// this는 window 또는 global을 참조
// use strict 모드에서는 undefined가 됨
2-2. 객체의 메서드 내부에서의 this
const obj = {
name: "Alice",
sayHello: function () {
console.log(this.name);
}
};
obj.sayHello(); // "Alice"
- 객체의 메서드 내부에서는 해당 객체(obj)를 참조
- this.name = "Alice"
// 객체 내부의 함수에서 this
const person = {
name: "Bob",
sayHello: function () {
function innerFunction() {
console.log(this.name);
}
innerFunction();
}
};
person.sayHello(); // undefined
- 내부 함수에서는 this가 undefined가 됨
this를 유지하는 방법
방법1. this를 변수에 저장
const person = {
name: "Charlie",
sayHello: function () {
const self = this;
function innerFunction() {
console.log(self.name);
}
innerFunction();
}
};
person.sayHello(); // "Charlie"
방법2. 화살표 함수 사용(this를 상속)
const person = {
name: "David",
sayHello: function () {
const innerFunction = () => {
console.log(this.name);
};
innerFunction();
}
};
person.sayHello(); // "David"
- 화살표 함수는 this를 부모 컨텍스트에서 상속받음
방법3. bind 사용
const person = {
name: "Eve",
sayHello: function () {
function innerFunction() {
console.log(this.name);
}
const boundFunction = innerFunction.bind(this);
boundFunction();
}
};
person.sayHello(); // "Eve"
- bind(this)를 사용하여 this를 강제로 설정
2-3. 생성자 함수에서 this
function Person(name) {
this.name = name;
}
const john = new Person("John");
console.log(john.name); // "John"
- 생성자 함수에서는 this가 새로 생성된 객체를 가리킨다.
2-4. 화살표 함수에서 this
const obj = {
name: "Foo",
sayHello: () => {
console.log(this.name);
}
};
obj.sayHello(); // undefined
- 화살표 함수의 this는 객체를 가리키지 않고, 부모 스코프(window 또는 global)를 참조
- 화살표 함수 내부에서는 this가 바인딩되지 않는다.
2-5. call, apply, bind를 사용한 this 변경
- call 사용
function sayHello() {
console.log(`Hello, my name is ${this.name}`);
}
const user = { name: "Jake" };
sayHello.call(user); // "Hello, my name is Jake"
- apply 사용
function introduce(age, city) {
console.log(`I am ${this.name}, ${age} years old from ${city}.`);
}
const user = { name: "Lily" };
introduce.apply(user, [25, "New York"]);
// "I am Lily, 25 years old from New York."
- bind 사용
function greet() {
console.log(`Hi, I am ${this.name}`);
}
const user = { name: "Michael" };
const boundGreet = greet.bind(user);
boundGreet(); // "Hi, I am Michael"
* call과 apply는 즉시 실행, bind는 새로운 함수를 반환
3. this 정리
상황 | this가 가리키는 대상 |
전역 공간 | window (또는 global) |
일반 함수 | window (use strict 모드에서는 undefined) |
객체의 메서드 | 해당 객체 |
객체 내부 함수 | 기본적으로 window, 해결방법 (self, bind, arrow function) |
생성자 함수 | 새로 생성된 객체 |
화살표 함수 | 부모 컨텍스트의 this를 상속 |
call, apply, bind 사용 | 명시적으로 설정한 객체 |
정리
this는 실행 컨텍스트에 따라 다르게 동작하며, 화살표 함수는 부모의 this를 상속 받는다.
call, apply, bind를 사용하면 this를 원하는 객체로 지정 가능
끝.
'JavaScript' 카테고리의 다른 글
JavaScript - 비동기 프로그래밍 (Promise, async / await) (0) | 2025.02.08 |
---|---|
JavaScript - 실행 컨텍스트와 콜 스택(Call Stack) (0) | 2025.02.04 |
JavaScript - 호이스팅(Hoisting) (0) | 2025.01.29 |
JavaScript - 스코프(Scope)와 클로저(Closure) (0) | 2024.12.27 |
JavaScript - JavaScript의 디버깅과 개발 도구 활용 (1) | 2024.12.21 |