DEV Community

Laxman Nemane
Laxman Nemane

Posted on

'new' keyword

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:

  1. A new empty object is created.
  2. The new object's prototype is set to the constructor function's prototype.
  3. The constructor function is called to the new object with 'this' set.
  4. 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

Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)