Class Constructor
suggest changeThe fundamental part of most classes is their constructor, which sets up each instance’s initial state and handles parameters passed to new.
It’s defined in a class block as though you’re defining a method named constructor, though it’s actually handled as a special case.
class MyClass {
constructor(option) {
console.log(`Creating instance using ${option} option.`);
this.option = option;
}
}
Example usage:
const foo = new MyClass('speedy'); // logs: "Creating instance using speedy option"
A class constructor cannot be declared static. Ordinary methods can. A class may also omit constructor, in which case the default constructor forwards its arguments to super(). A derived class that declares a constructor must call super() before using this.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents