DAMO'S BLOG

Remote Full-Stack Engineer | Supports North America/Europe Time Zones

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., stringnumberboolean, 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):

  1. In the newInstance function that simulates the behavior of new, how are the properties defined inside the constructor injected into the new object?
  2. Is new (new MyFunc().constructor)() executable?
Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *.

*
*

Tech Stack

Nestjs,PHP,Angular,React,Vue

Contact Me

地址
123 Main Street
New York, NY 10001

营业时间
星期一—五:9:00–17:00
星期六—日:11:00–15:00