Middle
How does the new operator work in JavaScript?
sobes.tech AI
Answer from AI
The new operator is used to create an instance of an object based on a constructor function.
When calling new ConstructorFunction(), the following steps occur:
- A new empty object is created in memory.
- The prototype of this new object is set to the
prototypeproperty of the ConstructorFunction. - The constructor
ConstructorFunctionis called with the execution context (this) set to the new object. The arguments passed toneware forwarded to the constructor. - If the constructor returns a non-primitive value (object, array, function, etc.), this value becomes the result of the
newcall. - If the constructor does not explicitly return a value or returns a primitive value (number, string, null, undefined, boolean, symbol, bigint), the result of the
newcall is the new object created in step 1.
Example:
function Person(name, age) {
// `this` points to the new object created by `new`
this.name = name;
this.age = age;
}
Person.prototype.greet = function() {
// `this` still points to the instance of the object
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
};
const person1 = new Person('Alexey', 30); // Call with new
console.log(person1); // { name: 'Alexey', age: 30 }
person1.greet(); // Hello, my name is Alexey and I am 30 years old.
console.log(person1 instanceof Person); // true
A similar behavior can be emulated without new using Object.create and call or apply:
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.greet = function() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
};
// Emulation of new
function customNew(constructor, ...args) {
const obj = Object.create(constructor.prototype); // Steps 1 and 2
const result = constructor.apply(obj, args); // Step 3
// Steps 4 and 5
return result !== null && typeof result === 'object' ? result : obj;
}
const person2 = customNew(Person, 'Maria', 25);
console.log(person2); // { name: 'Maria', age: 25 }
person2.greet(); // Hello, my name is Maria and I am 25 years old.