What “new” keyword does?

Abhishek Shastri
AltCampus
Published in
2 min readNov 20, 2018
source: https://cdn-images-1.medium.com/max/800/1*RoHlzKvEVoVizcwpqKSUAQ.jpeg

As we know in JavaScript almost everything is an object. Even a function is an object in JavaScript. The new keyword invokes a function in a special way and creates a new empty object. But there is a difference between creating an Object with new keyword and without new keyword.

The Object created with new keyword bind the Object to this keyword.

The new keyword does mainly four things for us.

1. A new empty Object is created.
2. The created Object Gets [[Prototype]] linked.
3. The created Object is set to this for that function call.
4. this(the newly constructed object) is automatically returned from the new-invoked function unless it explicitly returns a different Object.

Steps for creating User defined function

(i). Define an Object by writing a function.
(ii). Create an instance of the object with the new keyword.
Here new functionName = new FunctionName() but only if any parameter is not passed to the function.
(iii). We can always add a property to this defined object. Even we can add a property to object by adding this keyword to refer the object.

Creating a function with new keyword will add the methods or property of constructor function which are there in the prototype of the constructor function. Here adding the methods and property does not mean copying all the data from the prototype of the constructor function. Instead, the __proto__ is directly linked to the prototype of the constructor function.

Here newUser is an Object with property name as Sachin. But it also has Wish function attached to it but hidden to the user. This wish function is stored in __proto__ key of the Object newUser. Here the property of sayHi function is linked to the __proto__ of the newUser Object.

--

--