The new Keyword in JavaScript
The new keyword helps us create objects (instances) using constructor functions or classes. It works with functions and classes to initialize new objects. Under the hood, it also links the created object to the constructor’s prototype, allowing access to shared methods.
Constructor functions
First, let’s look at the constructor() inside classes. A class can have a constructor method that is used to initialize values when a new object is created.
It allows us to pass initial parameters and assign them to properties of the object.
class User {
constructor(name) {
this.name = name;
}
}
const u1 = new User("John");
With functions
function User(name) {
this.name = name;
}
const u1 = new User("John");
How new Links Prototypes
Every function in JavaScript has a prototype property. When an object is created using new, it gets linked to this prototype.
This means the object can access properties and methods defined on the constructor’s prototype through prototype chaining.
function Animal(name) {
this.name = name;
}
Animal.prototype.speak = function () {
return this.name + " makes a sound";
};
const dog = new Animal("Dog");
console.log(dog.speak());
Instances Created from Constructors
Each object created using the new keyword is called an instance of that constructor. All instances share the same structure but can have different values.
function Car(brand) {
this.brand = brand;
}
const car1 = new Car("Toyota");
const car2 = new Car("Honda");
Both car1 and car2 are instances of Car, and they inherit properties and methods defined in the constructor and its prototype.