new Keyword in JavaScript

In JavaScript, the "new" keyword is used to create a new and unique instance of an object from a constructor function. It binds this to the newly created instance, which by default looks in the global window for its value and gives wrong and unexpected outputs. Constructor functions are special functions that are used to define and initialize objects with a specific set of properties and methods.

Syntax:

new constructorFunction(arguments)

where constructorFunction is a class/function that specifies the type of the object instance and arguments are a list of values that the constructor will be called with.

Here's how the "new" keyword works:

Define a Constructor Function

First, you need to define a constructor function that will serve as a blueprint for creating objects. The constructor function is typically named with an initial capital letter to distinguish it from regular functions.

Example:

function Person(name, age)
{
    this.name = name;
    this.age = age;
}

Create an Instance

To create a new instance of an object, you use the "new" keyword followed by the constructor function name, using parentheses if there are arguments to be passed.

Example:

const john = new Person('John', 25);

Object Creation

When the "new" keyword is used, it creates a new empty object and assigns it to the "this" keyword inside the constructor function. The constructor function then initializes the object by setting its properties and methods using the "this" keyword.

Prototype Inheritance

Instances created with the "new" keyword automatically inherit properties and methods from the prototype object of the constructor function. This allows multiple instances to share common functionality without duplicating code.

Example:

Person.prototype.sayHello = function()
{
    console.log('Hello, my name is ' + this.name);
};
john.sayHello();
500 Internal Server Error

500 Internal Server Error