[JS] this

임찬혁·2023년 3월 16일
2

JavaScript

목록 보기
4/5
post-thumbnail

다른 언어들과 마찬가지로 JavaScript 에도 this 가 있습니다. 하지만 JavaScript 에서의 this 는 다른 언어들과는 조금 다르게 동작하는데, 이 부분을 헷갈려하는 경우가 많이 있습니다. 이번 포스트에서는 JavaScriptthis 에 대해 알아보겠습니다.

this와 메서드

this메서드(Method) 에서 주로 사용됩니다. 메서드객체(Object) 에 저장되어 있는 정보(프로퍼티)를 활용하는 경우가 많기 때문입니다.

let toy = {
  price: '$30',
  printPrice: function() {
    console.log(this.price);
  },
};

toy.printPrice();	// $30

위처럼 메서드 내부에서 this 를 사용하면, 메서드 를 호출한 객체 에 접근할 수 있습니다. printPrice() 를 호출한 객체toy 이기 때문에 thistoy 가 됩니다.

this 를 사용하지 않아도 같은 기능을 구현할 수는 있습니다.

let toy = {
  price: '$30',
  printPrice: function() {
    console.log(toy.price);
  },
};

toy.printPrice();	// $30

하지만 이렇게 구현하는 경우에는 의도치않은 버그가 생길 수 있습니다.

let toy = {
  price: '$30',
  printPrice: function() {
    console.log(toy.price);
  },
};
const food = toy;

toy = null;

food.printPrice();	// Uncaught TypeError: Cannot read properties of null (reading 'price')

food.printPrice() 에서는 toy 가 필요하지만 null 이 되었기 때문에 Uncaught TypeError: Cannot read properties of null (reading 'price') 에러가 발생하게 됩니다.

this의 동작방식

처음에 이야기한 것처럼, JavaScript 에서의 this 는 다른 언어들과 동작방식이 다릅니다.
C++, Java 와 같은 객체지향 언어에서 this 는 객체 자신(주소, 포인터 등등)을 가리킵니다.
JavaScriptthis런타임(프로그램 실행 중) 에 컨텍스트에 따라 결정됩니다. 따라서 객체 내부의 메소드 에서만 사용될 필요가 없고, 일반 함수 에서도 사용할 수 있습니다.

function printPrice() {
  console.log(this.price);
}

이렇게 선언한 함수를 특정 객체 에서 사용한다면 this 는 그 객체 를 가리킵니다.

function printPrice() {
  console.log(this.price);
}

let toy = {
  price: '$30',
};

let food = {
  price: '$20',
};

toy.printPrice = printPrice;
food.printPrice = printPrice;

toy.printPrice();	// $30
food.printPrice();	// $20

toy 에서 printPrice() 를 호출하면 thistoy 가 되고, food 에서 printPrice() 를 호출하면 thisfood 가 됩니다.

객체 없이도 함수 를 호출할 수 있지만, 브라우저인 경우에 thisWindow 전역객체가 됩니다.

엄격모드(strict mode)에서 thisundefined 가 됩니다. 따라서 this.price 처럼 속성에 접근하게 되면 에러가 발생합니다.

function printPrice() {
  console.log(this, this.price);
}

printPrice();	// Window {...}, undefined

쉽게 생각하면 this. 연산자 앞의 객체를 가리킨다고 생각하면 됩니다.

화살표 함수(Arrow Function)에서의 this

화살표 함수 에서 this 의 동작방식은 일반 함수 와는 또 다릅니다. 화살표 함수this일반 함수 인 외부 컨텍스트를 참조합니다.

let toy = {
  price: '$30',
  printPrice: function() {
    const print = () => {
      console.log(this.price);
    };
    
    print();
  },
};

toy.printPrice();	// $30

위 코드에서 print() 함수의 this 는 외부 컨텍스트 중 일반 함수printPrice() 함수의 this 를 참조하기 때문에 toy 가 됩니다.

let toy = {
  price: '$30',
  printPrice: function() {
    const print = () => {
      const nestedPrint = () => {
      	console.log(this.price);
      };
	  
      nestedPrint();
    };
    
    print();
  },
};

toy.printPrice();	// $30

위 코드에서처럼 중첩된 화살표 함수 인 경우에는 외부 컨텍스트 중 일반 함수printPrice() 함수의 this 를 참조하기 때문에 toy 가 됩니다.

마치며

어떤 언어를 학습하더라도 기본기가 제일 중요합니다. JavaScript 에서 헷갈리는 this 에 대한 개념을 확실히 잡고 좀 더 탄탄하고 명확한 코드를 작성할 수 있도록 해야겠습니다.

profile
개발새발자

0개의 댓글