class Car { constructor(brand, model, color) { this.brand = brand; // 브랜드명 this.model = model; // 모델명 this.color = color; // 색상 this.speed = 0; } // 엑셀을 작동한다. accelerate() {this.speed += 10;} // 브레이크를 작동한다. brake() {this.speed -= 10;} }
constructor()는 클래스 생성자 함수로서 클래스로부터 생성된 인스턴스를 초기화하기 위해 호출되는 함수라고 보면 된다.
위 코드와 같이 클래스를 이용하여 자동차의 기본적인 구조나 작동방식을 나타내는 기본 설계도를 완성시킬 수 있다.
const newCar = new Car("Hyundai", "Sonata", "Black"); // newCar라는 인스턴스 생성
newCar라는 변수에 인스턴스를 생성하면 아래와 같은 객체가 할당된다.
Car { brand: "Hyundai", model: "Sonata", color: "Black", speed: 0 }
작동방식
function Car(brand, model, color) { this.brand = brand; this.model = model; this.color = color; this.speed = 0; this.accelerate = function() { this.speed += 10; }; this.brake = function() { this.speed -= 10; }; }
class Car { constructor(brand, model, color) { this.brand = brand; this.model = model; this.color = color; this.speed = 0; } accelerate() { this.speed += 10; } brake() { this.speed -= 10; } }