What is the purpose of the `new` keyword?
TL;DR
The new
keyword in JavaScript is used to create an instance of a user-defined object type or one of the built-in object types that has a constructor function. When you use new
, it does four things: it creates a new object, sets the prototype, binds this
to the new object, and returns the new object.
The purpose of the new
keyword
Creating a new object
The new
keyword is used to create a new instance of an object. When you call a constructor function with new
, it creates a new object.
Setting the prototype
The new object’s internal [[Prototype]]
property is set to the constructor function’s prototype
property. This allows the new object to inherit properties and methods from the constructor’s prototype.
Binding this
to the new object
Inside the constructor function, this
refers to the new object that is being created. This allows you to add properties and methods to the new object.
Returning the new object
The new
keyword implicitly returns the new object created by the constructor function. If the constructor function explicitly returns an object, that object will be returned instead.