JS 1-3. JavaScript의 this

강연주·2024년 11월 12일

🙋‍♀️ 기술면접

목록 보기
46/112

3. JavaScript의 this가 어떤 값을 가지는지 상황별 설명

자바스크립트에서 this는 현재 실행 컨텍스트(context)에 따라 달라지는 특별한 객체를 참조한다. 실행 위치에 따라 this가 가리키는 대상이 달라지며, 자바스크립트에서는 주로 함수 내에서 this를 많이 사용한다.

기본적인 this 동작 방식

👝 전역 컨텍스트
: 전역 컨텍스트에서 this는 전역 객체(브라우저에서는 window)를 가리킨다.

🖥️ javascript

console.log(this); // window 객체 출력 (브라우저 환경 기준)

👝 메서드 호출
: 객체의 메서드 내부에서 this는 해당 객체를 가리킨다.

🖥️ javascript

const obj = {
    name: "John",
    sayName: function() {
        console.log(this.name);
    }
};
obj.sayName(); // "John" 출력

👝 생성자 함수
: 생성자 함수 내부에서 this는 새로 생성된 객체 인스턴스를 가리킨다.

🖥️ javascript

function Person(name) {
    this.name = name;
}
const person1 = new Person("Alice");
console.log(person1.name); // "Alice" 출력

👝 화살표 함수
: 화살표 함수에서 this는 상위 스코프의 this를 상속받아 사용.
그래서 this를 새로 바인딩하지 않는다.

🖥️ javascript

const obj = {
    name: "John",
    sayName: () => {
        console.log(this.name);
    }
};
obj.sayName(); // undefined (상위 스코프의 this가 window라면 undefined가 출력됨)

👝 명시적 바인딩
: call, apply, bind 메서드를 통해 this를 원하는 객체에 명시적으로 바인딩할 수 있다.

🖥️ javascript

function greet() {
    console.log(this.name);
}

const user = { name: "Jane" };
greet.call(user); // "Jane" 출력

➡️ 이처럼 this는 자바스크립트에서 상황에 따라 유동적으로 변경되므로,
코드 작성 시 의도를 정확히 이해하는 것이 중요하다.


call, apply, bind

💘 call, apply, bind

profile
아무튼, 개발자

0개의 댓글