• 모닥위키모닥위키
  • 모닥위키
위키
  • 임의문서
  • 주간인기
  • 문서
  • 시리즈
    AAAdddvvveeerrrtttiiissseeemmmeeennntttAdvertisement

    © 2025 modak.wiki All rights reserved.

      new, 생성자, instanceof 그리고 인스턴스

      Chapter 16 - new, Constructor, instanceof and Instances

      컴퓨터/IT학습
      lu

      luasenvy (luasenvy)

      CC BY 4.0 국제규약

      클래스와 인스턴스

      // 건물의 설계도
      class Building {
        constructor(name, door) {
          this.name = name;
          this.door = door;
        }
      
        getDoor() {
          return this.door;
        }
      }
      
      const sweetHome = new Building("luasenvy", 1); // 실제로 건설한 건물
      const nextBuilding = new Building("next", 3); // 실제로 건설한 건물
      const somewhereBuilding = new Building("somewhere", 2); // 실제로 건설한 건물
      

      클래스는 설계도라고 생각하면 된다. 이 설계도를 이용하여 실제로 만든 구현체를 인스턴스라고 한다. 집을 짓는다 생각하면 이해하기 쉽다.

      new and constructor

      생성자라고도 불리우는 constructor는 그냥 '초기화 함수'라고 기억하는 편이 이해하기 쉽다. 인스턴스를 new 키워드를통해 생성할 때 가장 먼저 호출되는데 인스턴스를 사용하기에 앞서 멤버변수들을 초기화하거나 필요한 작업들을 정의할 때 사용된다.

      자바스크립트 문법에서 new 키워드는 클래스로부터 새로운 인스턴스를 생성하기 위한 명령이다. 새로운 인스턴스가 생성되면서 인스턴스를 초기화 하기 위해 constructor()가 한 번 호출된다.

      class Person {
        constructor() {}
      }
      
      const person = new Person();
      
      person.constructor === Person // true
      
      if ( person instanceof Person ) // true
        console.log(true);
      

      자바스크립트에서 constructor는 클래스에 포함되고 constructor를 활용하여 자신의 타입이 무엇인지 비교하는 용도로도 활용된다. 클래스와 팩토리 디자인 패턴을 보면 알 수 있는데 person 인스턴스의 __proto__가 Person 프로토타입을 바라보고 다시 Person 프로토타입의 constructor가 Person 클래스를 가리키고 있기 때문에 person.constructor는 결국 Person 클래스를 가리키고 있는 것과 같기 때문이다. instanceof를 활용해도 동일한 작동을 한다.

      초판: 2024. 08. 18. 20:23:40

      © 2024 이 문서는 "CC BY 4.0 국제규약" 라이선스로 배포 되었습니다. 모든 권리는 저자에게 있습니다.

      new, 생성자, instanceof 그리고 인스턴스

      클래스와 인스턴스
      new and constructor