'new' keyword
Laxman Nemane
Posted on November 26, 2024
In JavaScript, the 'new' keyword creates a new instance of an object from a constructor function.
Purpose of the new Keyword:
- Object creation.
- Prototype Linkage.
- Binding 'this' and returning newly created object.
How It Works:
When you use the new keyword with a constructor function, the following steps are executed:
- A new empty object is created.
- The new object's prototype is set to the constructor function's prototype.
- The constructor function is called to the new object with 'this' set.
- If the constructor does not return an object, the newly created object is returned.
Example :
Here's a concise code example that demonstrates the use of the new keyword in JavaScript, covering all the essential steps involved in object creation, prototype linkage, and binding 'this'.
// Step 1: Define a constructor function
function Car(make, model) {
this.make = make; // Step 3: Bind properties to the new object
this.model = model;
}
// Step 4: Add a method to the Car prototype
Car.prototype.getDetails = function() {
return `${this.make} ${this.model}`;
};
// Step 2: Create a new instance of Car using the new keyword
const myCar = new Car('Toyota', 'Corolla');
// Using the method from the prototype
console.log(myCar.getDetails()); // Output: Toyota Corolla
// To demonstrate the prototype linkage
console.log(myCar instanceof Car); // Output: true
Summary
In summary, the new keyword is essential for object-oriented programming in JavaScript. It enables the creation of new instances of objects, establishes prototype inheritance, binds the context of this, and handles the return of the created object. Understanding how new works is crucial for effectively using constructor functions and classes in JavaScript.
Posted on November 26, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 27, 2024