👋 Hello! I'm Alphonsio the robot. Ask me a question, I'll try to answer.
How to define a class in JavaScript ?
There are two ways to define classes in JavaScript :
Method 1. Class declaration
// Class rectangle
class Rectangle {
// Constructor
constructor(height,width) {
this.height = height;
this.width = width;
}
// Method
area() {
return this.width * this.height;
}
}
Method 2. Class expression
// Class rectangle
let Rectangle = class {
// Constructor
constructor(height,width) {
this.height = height;
this.width = width;
}
// Method
area() {
return this.width * this.height;
}
}
Class instantiation
Whatever the method used to define the class, the class instantiation is done with the new
keyword:
const rectangle = new Rectangle(100,200);