Home > Web Front-end > JS Tutorial > &#new&# keyword

&#new&# keyword

Barbara Streisand
Release: 2024-11-30 02:02:14
Original
960 people have browsed it

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

Copy after login

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.

The above is the detailed content of &#new&# keyword. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template