[JavaScript] 클래스(class)와 생성자 함수 의 차이

iberis2·2023년 1월 15일
0

ES6 이후 클래스(class) 문법이 생기면서, 그 이전까지 생성자 함수로 만든 객체와 3가지 차이점이 생겼다.

  1. for... in... 문으로 조회했을 때 매서드의 노출 여부
  2. new 없이 객체를 생성했을 때 오류 여부
  3. class 명시 여부

for in문 조회시 매서드 노출

클래스로 만든 인스턴스 객체를 for in 문으로 조회했을 때, 매서드는 열거되지 않는다.
반면 생성자 함수로 만든 객체를 for in 문으로 조회하면 매서드도 같이 열거된다.

  • 해당 프로퍼티가 원형 객체의 프로퍼티가 맞는지 확인하기 위해서는 hasOwnProperty 를 사용해야한다. (상속된 프로퍼티에는 false를 반환)
/* 생성자 함수로 정의하는 방식 */
function Car1(brand, name, color) {
  this.brand = brand;
  this.name = name;
  this.color = color;
}

Car1.prototype.drive = function () {
  console.log(`${this.name}의 운전을 시작합니다`);
};

const car1 = new Car1("hyundai", "avante", "blue");
for (element in car1) {
  console.log(`${element}: ${car1[element]}`);
}
/*brand: hyundai
name: avante
color: blue
drive: function () {
  console.log(`${this.name}의 운전을 시작합니다`);
} */

// hasOwnProperty 매서드는 상속된 프로퍼티에는 false를 반환한다.
console.log(car1.hasOwnProperty("drive")); // false
/* ES6 이후 class로 정의하는 방식 */
class Car2 {
  constructor(brand, name, color) {
    this.brand = brand;
    this.name = name;
    this.color = color;
  }

  drive() {
    console.log(`${this.name}의 운전을 시작합니다`);
  }
}

const car2 = new Car2("hyundai", "avante", "blue");
for (element in car2) {
  console.log(`${element}: ${car2[element]}`);
}
/*brand: hyundai
name: avante
color: blue */

new 미사용시 에러

클래스로 인스턴스 객체를 만들 때 'new'를 사용하지 않으면 에러가 발생한다.
반면 생성자 함수로 객체를 만들 때 'new'를 사용하지 않아도 함수의 값을 변수에 할당하는 것처럼 동작하기 때문에 에러가 발생하지는 않는다.

  • 다만 생성자 함수에 return 값이 없으므로 해당 변수에는 아무 값도 할당되지 않는다.
/* 생성자 함수로 정의하는 방식 */
function Car1(brand, name, color) {
  this.brand = brand;
  this.name = name;
  this.color = color;
}

Car1.prototype.drive = function () {
  console.log(`${this.name}의 운전을 시작합니다`);
};

const car1 = Car1("hyundai", "avante", "blue");
console.log(car1); // undefined
/* ES6 이후 class로 정의하는 방식 */
class Car2 {
  constructor(brand, name, color) {
    this.brand = brand;
    this.name = name;
    this.color = color;
  }

  drive() {
    console.log(`${this.name}의 운전을 시작합니다`);
  }
}

const car2 = Car2("hyundai", "avante", "blue");
// TypeError: Class constructor Car2 cannot be invoked without 'new'

class 명시 여부

클래스로 만든 인스턴스 객체를 콘솔에서 확인해보면 constructor에 class가 명시되어 있다.
반면 생성자 함수로 만든 객체를 콘솔에서 확인해보면 constructor에 class를 확인할 수 없다.

profile
React, Next.js, TypeScript 로 개발 중인 프론트엔드 개발자

0개의 댓글