If you have several objects that share the same implementation, you can use a constructor function to create them.
Any function can be a constructor function as long as it is invoked using the new keyword
function createSillyExample() {}
const objectCreatedFromSillyExample = new createSillyExample();
// result: {}
class Human {
constructor(name) {
this.name = name;
}
getName() {
return this.name;
}
}
Here's what's happening here:
- A new variable Human is created and it's assigned to the constructor function in the "class" from above;
- getName is a property, which is a method on the prototype of the constructor function;
You are not forced to set constructor method in the class. If not provided, JS engine will provide the following:
- constructor() {}