Web/Javascript
[javascript] 클래스(Class)
클리엘
2021. 2. 26. 15:31
728x90
Javascript에서도 Class는 Prototype을 사용하던 이전방식에서 벗어나 좀 더 깔끔하게 코드가 만들어질 수 있도록 해줍니다.
class Car {
constructor(speed) {
this.speed = speed;
}
currentSpeed()
{
return this.speed;
}
stop() {
this.speed = 0;
}
static acc(speed) {
return this.speed + speed;
}
};
var car = new Car(100);
car.stop();
기존에는 prototype을 통해 함수를 정의하고 직접 속성에 메서드를 할당하는 방식을 따랐지만 필요한 함수는 함수그대로 정의하고 정적 함수의 경우 static을 붙여주는 것만으로 끝낼 수 있습니다.
클래스는 정의하는것 뿐아니라 기존 클래스에서 상속해 새로운 클래스를 생성하는 방법 또한 간결해졌습니다.
class Truck extends Car {
constructor(speed) {
super(speed);
this.speed = speed;
}
stop()
{
super.stop();
}
}
상속은 extends로 구현되며 super를 사용해 부모의 생성자 함수나 메서드를 호출할 수 있습니다.
728x90