What happens when using new with a constructor function in JavaScript?
When using the new operator to call a function (known as a constructor) in JavaScript, the following four key steps occur:
1. A new empty object is created
The JavaScript engine first creates a brand-new empty object:
const newObj = {};
2. The new object’s prototype ([[Prototype]]) is set
The internal prototype ([[Prototype]], accessible via __proto__ or Object.getPrototypeOf()) of the new object is linked to the constructor function’s prototype property:
newObj.__proto__ = Constructor.prototype;
This allows the new object to inherit properties and methods defined on the constructor’s prototype.
3. The constructor function is executed with this bound to the new object
The body of the constructor function runs, and within it, this refers to the newly created object. Typically, the constructor adds properties or methods to this:
Constructor.call(newObj, ...args);
For example:
function Person(name) {
this.name = name; // `this` points to the new object
}
4. The new object is returned (unless the constructor explicitly returns an object)
- If the constructor does not return a value explicitly, or returns a primitive value (e.g.,
string,number,boolean, etc.), the newly created object is returned automatically. - If the constructor explicitly returns an object, that object is returned instead of the newly created one.
Example returning an object:
function Foo() {
this.a = 1;
return { b: 2 }; // This object is returned, not `this`
}
const obj = new Foo();
console.log(obj); // { b: 2 }
But if it returns a primitive:
function Bar() {
this.a = 1;
return 42; // Ignored
}
const obj = new Bar();
console.log(obj); // { a: 1 }
Summary: The behavior of new can be simulated like this
function myNew(Constructor, ...args) {
const obj = Object.create(Constructor.prototype);
const result = Constructor.apply(obj, args);
return (typeof result === 'object' && result !== null) ? result : obj;
}
Reflection / Bonus Questions (a.k.a. “Looking for trouble” section):
- In the
newInstancefunction that simulates the behavior ofnew, how are the properties defined inside the constructor injected into the new object? - Is
new (new MyFunc().constructor)()executable?