The new
keyword in JavaScript is used to create an instance of an object or to invoke a constructor function. It allocates memory for the object and sets up a link between the object and its prototype.
Syntax:
javascriptnew Constructor([arguments])
Usage:
Creating an instance of an object:
The
new
keyword is commonly used to create an instance of a user-defined object. It invokes the constructor function and initializes the object.javascriptfunction Person(name, age) { this.name = name; this.age = age; } const john = new Person("John", 25); console.log(john.name); // Output: John console.log(john.age); // Output: 25
In the above example, the
Person
function acts as a constructor, and thenew
keyword creates a new instance of thePerson
object with the specified name and age.Invoking a constructor function:
The
new
keyword is used to invoke a constructor function and execute the code inside it.javascriptfunction Car(make, model) { this.make = make; this.model = model; this.startEngine = function() { console.log("Engine started!"); } } const myCar = new Car("Toyota", "Camry"); myCar.startEngine(); // Output: Engine started!
In the above example, the
new
keyword invokes theCar
constructor, which sets themake
andmodel
properties and defines a methodstartEngine
.
Explanation:
When the new
keyword is used with a function, it performs the following steps:
- A new object is created, and its
this
value is set to the newly created object. - The function specified after
new
is invoked with thethis
value referring to the newly created object. - The newly created object is automatically linked to its prototype object through the
prototype
property of the constructor function. - If the constructor function does not explicitly return an object, the
new
expression evaluates to the newly created object. Otherwise, the returned object is used instead.
The new
keyword is essential for object-oriented programming in JavaScript, as it allows the creation of instances and the initialization of their properties and methods.
Note: It's important to use the new
keyword when creating instances of objects to ensure that the this
value is correctly set within the constructor function. Forgetting to use new
may lead to unexpected behavior or errors.
0 Comments