ECMAScript question detail
Classes
The classes are introduced as syntactic sugar over existing prototype based inheritance and constructor functions. So this feature doesn't bring new object-oriented inheritance model to JavaScript.
There are two ways to define classes,
- Class declarations:
class Square {
constructor(length) {
this.length = length;
}
get area() {
return this.length * this.length;
}
set length(value) {
this.length = value;
}
}
- Class expressions:
const square = class Square {
constructor(length) {
this.length = length;
}
get area() {
return this.length * this.length;
}
set length(value) {
this.length = value;
}
}
You can use extend keyword to use inheritance. This enables the subclass to get all features of a parent class.
class Vehicle {
constructor(name) {
this.name = name;
}
start() {
console.log(`${this.name} vehicle started`);
}
}
class Car extends Vehicle {
start() {
console.log(`${this.name} car started`);
}
}
const car = new Car('BMW');
console.log(car.start()); // BMW car started
Note: Even though ES6 classes looks similar to classes in other object oriented languages, such as Java, PHP, etc but they do not work exactly the same way.