Sobes.tech
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:

  1. A new empty object is created in memory.
  2. The prototype of this new object is set to the prototype property of the ConstructorFunction.
  3. The constructor ConstructorFunction is called with the execution context (this) set to the new object. The arguments passed to new are forwarded to the constructor.
  4. If the constructor returns a non-primitive value (object, array, function, etc.), this value becomes the result of the new call.
  5. 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 new call 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.