Classes cheatsheet
Basic usage
Classes provide a simpler, more intuitive way of creating objects and organising inheritance.
class Element {
height = 10;
width = 10;
calcArea() {
return this.height * this.width;
}
}
const element = new Element();
element.height; // 10
element.width; // 10
element.calcArea(); // 100Сonstructor is a special method required to initialise the passed values.
class Element {
constructor(width, height) {
this.width = width;
this.height = height;
}
calcArea() {
return this.height * this.width;
}
}
const rectangle = new Element(20, 30);
const square = new Element(25, 25);Сlass inheritance
For class inheritance is used the keyword extends, super is used to pass values to the parent constructor
Inherited methods can be completely overwritten
super keyword can call the parent version of the method
Getters & setters
Getters and setters work in the same way as in objects. They are essentially functions that execute on getting and setting a value, but look like regular properties to an external code.
Static methods & properties
Static methods/properties are called without creating an instance of their class.
Static properties/methods are not available for instances.
But static properties/methods can be inherited
Operator instanceof
The instanceof operator allows to check whether an object belongs to a certain class
It also works with function-constructors
Mixins
Mixin is just objects. They are used to add additional properties/methods to existing classes. The mixins themselves are not used.
Last updated