Ticker

6/recent/ticker-posts

New Keyword in JavaScript

New Keyword in JavaScript

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:

javascript
new Constructor([arguments])

Usage:

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

    javascript
    function 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 the new keyword creates a new instance of the Person object with the specified name and age.

  2. Invoking a constructor function:

    The new keyword is used to invoke a constructor function and execute the code inside it.

    javascript
    function 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 the Car constructor, which sets the make and model properties and defines a method startEngine.

Explanation:

When the new keyword is used with a function, it performs the following steps:

  1. A new object is created, and its this value is set to the newly created object.
  2. The function specified after new is invoked with the this value referring to the newly created object.
  3. The newly created object is automatically linked to its prototype object through the prototype property of the constructor function.
  4. 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.

Post a Comment

0 Comments