ES6 이후 클래스(class) 문법이 생기면서, 그 이전까지 생성자 함수로 만든 객체와 3가지 차이점이 생겼다.
클래스로 만든 인스턴스 객체를 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'를 사용하지 않아도 함수의 값을 변수에 할당하는 것처럼 동작하기 때문에 에러가 발생하지는 않는다.
/* 생성자 함수로 정의하는 방식 */
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'
클래스로 만든 인스턴스 객체를 콘솔에서 확인해보면 constructor에 class가 명시되어 있다.
반면 생성자 함수로 만든 객체를 콘솔에서 확인해보면 constructor에 class를 확인할 수 없다.