Last updated on February 28, 2020
Hello guys, this post helps you to learn one important idea of enforcing the new
operator when creating an object with the function constructor pattern.
Sometimes, developers don’t aware that to use a new keyword while creating an object so will checkout that here forcing ‘new’ with Constructor Function in Javascript.
Let’s see along with the coding snippet of real use case,
function User(options) {
this.name = options.name || 'Srinivasan';
this.emailId = options.emailId || '';
this.contactNumber = options.contactNumber || '';
}
const newUser = User();
console.log(newUser); (a)
If we execute the line (a), we would get undefined. Then you may ask, where these variable assignments are gone. By the time it’s available from the global scope and you can access those by window.name, window.emailId
.
If we don’t want to add up our properties to the global scope, then we would end up creating an object with the new operator.const newUser = new User();
console.log(`${newUser.name},${newUser.emailId}`);
But, we cannot force other developers to use the new keyword explicitly when trying to create an object out of our function.
To overcome that situation, we can rewrite our function as below.
function User(options) {
if(!(this instanceOf User)) {
return new User();
}
this.name = options.name || 'Srinivasan';
this.emailId = options.emailId || '';
this.contactNumber = options.contactNumber || '';
}
const newUser = new User();
const anotherUser = User();
This piece of code would make the difference and our code will also be more robust.if(!(this instanceOf User)) {
return new User();
}
These are all small details but more powerful. Who knows if you’re about to create your own javascript library in near future this kind of pattern would be more needed.
Additionally, I’ve used one more pattern have you guys noticed it while creating function? If so you can please share that pattern in the comments section.