Advance JavaScript (DOM, BOM, Web API) / Object Oriented Programming

new Keyword

In JavaScript, the new keyword is used to create an instance of a user-defined object type or one of the built-in object types that has a constructor function. When you use new with a constructor function, it performs the following steps:

  1. Creates a new empty object.

  2. Sets the [[prototype]] of the new object to the .prototype property of the constructor function.

  3. Binds this to the new object within the constructor function.

  4. Executes the constructor function with the provided arguments.

  5. Returns the new object unless the constructor function returns a non-primitive value (an object or a function), in which case that value is returned instead.

Here is an example to illustrate how the new keyword works:

Example: Using new with a Constructor Function

// Define a constructor function
function Person(name, age) {
    this.name = name;
    this.age = age;

    // Method to greet
    this.greet = function() {
        console.log(`Hello, my name is ${this.name} and I am ${this.age} years 
        old.`);
    };
}

// Use `new` to create an instance of Person
const john = new Person('John', 30);
const jane = new Person('Jane', 25);

// Call the greet method on the instances
john.greet(); 
// Output: Hello, my name is John and I am 30 years old.
jane.greet(); 
// Output: Hello, my name is Jane and I am 25 years old.

How new Works in Steps

  1. Create a new object:

    let instance = {}; // new empty object
  2. Set the prototype:

    instance.__proto__ = Person.prototype; // Set the prototype
  3. Bind this and execute the constructor:

Person.call(instance, 'John', 30); 
// Execute the constructor with `this` bound to `instance`
  1. Since .call() sets this = instance, every line inside the constructor becomes:

    this.name = name;   →  instance.name = "John"
    this.age = age;     →  instance.age = 30
    this.greet = ...    →  instance.greet = function() { ... }

    The constructor does not return the object.

    It only fills instance with values.

    After that, the “new” mechanism returns the instance object.

    instance = {
      name: "John",
      age: 30,
      greet: function() { ... }
    }
  1. Return the new object:

return instance;

Key Points

  • new is used with constructor functions and classes to create instances.

  • The new object’s prototype is set to the constructor’s prototype.

  • this inside the constructor function refers to the new object.

  • The constructor function initializes the new object.

  • The new keyword is essential for ensuring the correct creation and setup of the new object. Without new, the function would not behave as a constructor and this would not refer to a new instance.