Course contentsShow
← JavaScript
Lesson 742 of 2,72317. Prototypes and InheritanceFree lesson

Manually Simulating 'new'

Write a function that replicates 'new' behavior to solidify understanding of all four steps.

Manually Simulating 'new'

You'll learn how to write a function that replicates what the new operator does behind the scenes, cementing your understanding of object creation.

The Core Idea

Now that you know the four steps new performs (creating an empty object, linking its prototype, calling the constructor with this bound, and returning the object), you can write your own function that does the same thing. This manual simulation helps you truly understand that new isn't magic—it's just a sequence of operations you can perform yourself.

Building Your Own 'new'

Here's how to create a myNew function that mimics new:

function myNew(constructor, ...args) {
  // Step 1: Create a new empty object
  const obj = {};
  
  // Step 2: Link its __proto__ to constructor.prototype
  Object.setPrototypeOf(obj, constructor.prototype);
  
  // Step 3: Call the constructor with obj as 'this'
  const result = constructor.apply(obj, args);
  
  // Step 4: Return obj unless constructor returned an object
  return (typeof result === 'object' && result !== null) ? result : obj;
}

// Test it
function Dog(name) {
  this.name = name;
}

Dog.prototype.bark = function() {
  return `${this.name} barks!`;
};

const fido = myNew(Dog, 'Fido');
console.log(fido.bark()); // "Fido barks!"
console.log(fido instanceof Dog); // true

This function accepts a constructor and any arguments, then performs all four steps manually. It even handles the edge case where a constructor explicitly returns an object.

Key Takeaway:
Simulating new manually reveals it's just creating an object, linking prototypes, invoking the constructor, and returning—no mystery, just JavaScript you already understand.