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 objectswith 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();
Returning the Instance
The constructor function does not need to explicitly return the newly created object. It is automatically returned when using the "new" keyword. If the constructor function does return an object explicitly, that object will be returned instead of the newly created instance.
Example:
function Person(name) {
this.name = name;
return { greeting: 'Hello' };
}
const john = new Person('John');
console.log(john.greeting);
Hello
Conclusion
The "new" keyword is a powerful tool in JavaScript for creating objects with a consistent structure and behavior. It enables you to define and initialize object instances using constructor functions, allowing you to work with object-oriented programming principles in JavaScript.