this는 객체 또는 함수와 같이 사용되는 키워드이다.
객체 내에서 사용되는 this는 호출방식에 따라 가리키는 것이 달라질 수 있다.
1. 함수가 객체의 메서드로 호출되는 경우
this는 해당 객체를 나타낸다.
const user = {
name: 'Alice',
hi: function() {
console.log(`Hello, my name is ${this.name}`);
}
};
user.hi(); // "Hello, my name is Alice"
2. 생성자(constructor)함수로 호출된 경우
this는 새로 생성된 인스턴스를 가리킨다.
function User (name, age) {
this.name = name;
this.age = age;
this.hi: function() {
console.log(`Hello, my name is ${this.name}`);
}
};
const Alice = new User("Alice", 20);
user.hi(); // "Hello, my name is Alice"
3. 함수가 매서드가 아닌 일반적인 함수로 호출되는 경우
use strict 모드가 아닌 경우 this는 window(전역) 객체를 가르킨다.
use strict 모드인 경우 this는 undefined가 된다.
따라서 this가 예기치 못하게 전역객체를 가리키게 될 수 있으니 항상 'use strict'를 사용하는 것이 좋다.
"use strict";
function hi(){
console.log(`Hello, my name is ${this}`);
};
hi(); //undefined
'JAVASCRIPT' 카테고리의 다른 글
(Javascript) 논리 연산자 &&과 ||의 단축 평가 (0) | 2024.05.23 |
---|---|
(Javascript) hoisting(호이스팅)이란? 발생 배경, 종류, TDZ (0) | 2024.05.05 |
(Javascript) fetch를 이용해서 api 가져오기 , 사용법, 작동 과정 (0) | 2024.04.27 |
(Javascript) promise, async&await의 이해와 활용 (0) | 2024.04.26 |
(Javascript) local storage에 값 저장하기 (0) | 2024.04.18 |