본문 바로가기

JAVASCRIPT

(Javascript) this란 무엇인가? this 사용방법

 

 

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 모드가 아닌 경우 thiswindow(전역) 객체를 가르킨다.

use strict 모드인 경우 thisundefined가 된다.

 

따라서 this가 예기치 못하게 전역객체를 가리키게 될 수 있으니 항상 'use strict'를 사용하는 것이 좋다.

"use strict";

function hi(){
	console.log(`Hello, my name is ${this}`);
};

hi(); //undefined