Why new keyword should be used while instantiating JavaScript class

The new keyword is used to instantiate prototypical class or other objects. But why we need new keyword to initialize it, when you to try to initialize it without new will not throw any error at all then why should I use new before my class to instantiate it.

The answer is simple new keyword will set the ‘this’ to the new object created using function instead of global scope”.

If you didn’t provided new keyword then the context will be set to window(global scope).

You can see the difference in the below code example.

var fn = function (){
       this.a = 2;
       return this;
}

Instantiating fn without new keyword.

 var f = fn();  //`this` refers window here.

Instantiating fn with new keyword.

 var f = new fn();  //`this` refer object created by `fn` here.

Even though using new keyword is the best practice to instantiate class, most of the time, the users will skip them as it doesn’t provide any error at all.

We can use the below simple workaround to enforce the instantiating process using new keyword. Then the above fn will become as below.

 var fn = function (){
       if(!(this instanceof fn)) //workaround to resolve this problem.
          return new fn();
       this.a = 2;
       return this;
}

Now instantiating without new will also set this to the current object.

 var f = fn();  //this refer to fn here.

Instantiating class/function without new keyword in ES6 will throw TypeError.

Happy Scripting… 🙂

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s