Syntax
class class-name [ extends other class] {
//public or private fields
// constructor
//get and set property
//function
}
Class declarations
we are declaring a class using the class keyword with the name of the class 'Rectangle' in JavaScript.
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width; }
Class expressions
A class expression is another way to declare a class. Class expressions can be named or unnamed class declarations. This class will access by temporary name.
temporary_name.function-name() and temporary_name.fields-name
// unnamed class
let Rectangle = class {
constructor(height, width) {
this.height = height;
this.width = width;
}
};
Constructor
Constructor is a special method for creating and initializing a variable created with a class in JavaScript. There is only one constructor method in JavaScript, A SyntaxError will be throw if the class contains more than one constructor method. A constructor can use the super keyword to call the constructor of the superclass.
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
// Getter property
get area() {
return this.calcArea();
}
// Method
calcArea() {
return this.height * this.width;
}
}
const square = new Rectangle(10, 10);
console.log(square.area); // 100
Field declarations
Public field declarations
class Rectangle {
height = 0;
width;
constructor(height, width) { this.height = height;
this.width = width;
}
}
Private field declarations
class Rectangle {
#height = 0;
#width;
constructor(height, width) {
this.#height = height;
this.#width = width;
}
}
Extends the superclass
The extends keyword is used in class to create a class as a child of a parent class.
//Parent Class declaration
class Animal { constructor(name) { this.name = name; } speak() { console.log(`${this.name} makes a noise.`); } }
//Child Class declaration
class Dog extends Animal { constructor(name) { super(name); // call the super class constructor and pass in the name parameter } speak() { console.log(`${this.name} barks.`); } } let d = new Dog('Mitzie'); d.speak(); // Mitzie barks.