If you come from a classical object-oriented language, then constructors are second nature to you. They are a recent phenomenon in JS. If you utilize something like TypeScript, which is a superset of JS, then you utilize constructors all the time. In vanilla JS, constructors are simply function objects. This might create a problem wherein a constructor might be called as a “regular” function. We do not want that now do we? 😉
So how to prevent this. First, let’s look at the problem…
// Constructor. Note the casing. This is accepted practice for constructor casing in JS
function MyConstructor() {
console.log('This is my constructor that does some cool stuff!');
}
// Call constructor like a function
MyConstructor(); // outputs 'This is my constructor that does some cool stuff!' to the console.
You see the problem? This is not how you use a construction in classic object-oriented fashion. The construction is use to instantiate objects, not run directly. We can fix this with a bit of if logic…
function MyConstructor() {
if(!(this instanceof MyConstructor)) {
throw new Error('What are you doing? You are not supposed to call a constructor like a function!');
}
console.log('This is my constructor that does some cool stuff!');
}
// Call constructor like a function
MyConstructor(); // outputs 'What are you doing? You are not supposed to call a constructor like a function!' to the console.
The aforementioned code will throw an error and output the error message because we are attempting to call MyConstructor like a regular function and it is not an instance of MyConstructor. It IS MyConstructor. We would have to do something like…
function MyConstructor() {
if(!(this instanceof MyConstructor)) {
throw new Error('What are you doing? You are not supposed to call a constructor like a function!');
}
console.log('This is my constructor that does some cool stuff!');
}
// Create instance of MyConstructor
let myConstructorInstance = new MyConstructor(); // outputs 'What are you doing? You are not supposed to call a constructor like a function!' to the console.
Now the error will not be thrown and you can use the instance throughout your code. Granted, the constructor code doesn’t really do anything, but hopefully, you get the point. You can now call properties and methods that the constructor has from the instance. I hope you find this useful.
Happy Coding!
Clay Hess