Forem

Laxman Nemane
Laxman Nemane

Posted on

2

'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.

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay