자바스크립트 클래스를 프로토타입보다 사용하는 이유는 무엇인가요?
- 문법적인 간결함: 클래스는 프로토타입보다 문법적으로 더 간결하고 직관적입니다. 프로토타입을 사용할 때에는 prototype 객체에 메서드를 추가하고 생성자 함수를 정의해야 합니다. 하지만 클래스를 사용하면 메서드를 클래스 내부에 정의하고, 객체를 생성할 때에는 new 키워드를 사용하여 바로 인스턴스를 생성할 수 있습니다.
예시 코드:
// 프로토타입을 사용하는 방법
function Car(make, model) {
this.make = make;
this.model = model;
}
Car.prototype.startEngine = function() {
console.log('Engine started');
};
var myCar = new Car('Hyundai', 'Tucson');
myCar.startEngine();
// 클래스를 사용하는 방법
class Car {
constructor(make, model) {
this.make = make;
this.model = model;
}
startEngine() {
console.log('Engine started');
}
}
const myCar = new Car('Hyundai', 'Tucson');
myCar.startEngine();
- 상속의 편의성: 클래스는 상속을 훨씬 간편하게 구현할 수 있는 문법을 제공합니다. 클래스를 상속받는 하위 클래스를 만들 때에는
extends
키워드를 사용하여 간단히 상속 관계를 정의할 수 있습니다. 또한super
키워드를 사용하여 부모 클래스의 생성자나 메서드를 호출할 수 있습니다. 이를 통해 코드의 가독성과 재사용성을 높일 수 있습니다.
예시 코드:
// 프로토타입을 사용하는 방법
function Vehicle(make, model) {
this.make = make;
this.model = model;
}
Vehicle.prototype.startEngine = function() {
console.log('Engine started');
};
function Car(make, model, color) {
Vehicle.call(this, make, model);
this.color = color;
}
Car.prototype = Object.create(Vehicle.prototype);
Car.prototype.constructor = Car;
var myCar = new Car('Hyundai', 'Tucson', 'Blue');
myCar.startEngine();
// 클래스를 사용하는 방법
class Vehicle {
constructor(make, model) {
this.make = make;
this.model = model;
}
startEngine() {
console.log('Engine started');
}
}
class Car extends Vehicle {
constructor(make, model, color) {
super(make, model);
this.color = color;
}
}
const myCar = new Car('Hyundai', 'Tucson', 'Blue');
myCar.startEngine();
위의 두 가지 이유로 인해, 클래스를 사용하는 것이 프로토타입보다 더 효율적이고 직관적입니다. 하지만 기존에 프로토타입을 사용하던 코드나 라이브러리와의 호환성을 고려해야 하므로, 상황에 맞게 선택하여 사용해야 합니다.
#자바스크립트 #클래스