Class syntax has been added to ES6. The underlying inheritance model is still prototypal but the class syntax can make it easier to reason about relationships. To create a class just use the class
keyword. Classes can be created with class expressions or class declarations. Unlike function declarations, class declarations are not hoisted.
// class declaration
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
}
// class expression (unnamed)
var Square = class {
constructor(width) {
this.width = width;
}
};
ES6 classes support super
, constructor
, get
, set
, and static
methods. Inheritance is achieved with the extends keyword.
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
get color() {
return this.color;
}
set color(c) {
this.color = c;
}
// Read only property
get dimensions() {
return "height: " + this.height + ", width: " + this.width;
}
static area(rectangle) {
return rectangle.width * rectangle.height;
}
}
class Square extends Rectangle {
constructor(width) {
super(width, width);
}
}
const s = new Square(10);
console.log(s.width);//=> 10
console.log(s.dimensions);//=> "height: 10, width: 10"
console.log(Rectangle.area(s));//=> 100
Classes can have computed method names, including setters and getters, and generator methods.
class Rectangle {
constructor(width, height) {
this.width = width;
this.height = height;
}
['perimeter']() {
return (this.width * 2) + (this.height * 2);
}
get ['area']() {
return this.width * this.height;
}
* dimensions() {
yield this.width;
yield this.height;
}
}
const r = new Rectangle(3, 5);
console.log(r.perimeter());//=> 16
console.log(r.area);//=>15
for (let x of r.dimensions()) {
console.log(x);//=> 3, 5
}