Classes in ES6
Posted on August 02, 2018
- and tagged as
- javascript
ES6 gave us the ability to create classes in Javascript without using prototypes. Class based components are commonly used in React as they allow state to be stored amongst other things.
class Car {
// a constructor is a method which runs when the class is instantiated
// constructors are used to define default properties a newly created object should have
constructor(make, model, color) {
this.make = make
this.model = model
this.color = color
}
// to create a method, we define it in the class.
vroom() {
console.log(`${this.model}'s go vrooooom`)
}
}
To instantiate a class:
let car1 = new Car("Nissan", "Pulsar", "Silver")
console.log(car1.model)
"Pulsar"
car1.vroom()
"Pulsar's go vrooooom"
Subclasses
Subclasses allow us to extend existing classes.
class ElectricCar extends Car {
constructor(make, model, color, batterykWh) {
// to inherit properties we need to use the super() function
super(name, model, color);
this.batteryPower = batterykWh;
}
horsePowerHour() {
return this.batteryPower * 1.3428
}
}
let car2 = new ElectricCar("Tesla","S","Black",81)
car2.horsePowerHour()
"108.7668"