DEV Community

Cover image for Recreating `new` keyword in Javascript from scratch
Tilak Madichetti
Tilak Madichetti

Posted on

Recreating `new` keyword in Javascript from scratch

The best way to understand anything is to re-write it from scratch on your own

We are gonna do just that. So go grab yourself a 🍺, drop a huge ❤️ and chelax as we dive right into it.

Here's what we already do


function Person(name, age) {
  this.name = name;
  this.age = age;
}

Person.prototype.describe = function () {
  console.log(`I am ${this.name} , ${this.age} years of age ! `);
}

const client = new Person('Vladimir', 32);
client.describe();

Enter fullscreen mode Exit fullscreen mode

That outputs , I am Vladimir, 32 years if age !

Our goal is to change the line that has the new keyword to a more custom one like:

const client = spawn(Person, 'Vladimir', 32);
Enter fullscreen mode Exit fullscreen mode

where spawn is our own function that we create which should substitute new


function spawn(constructor, ...args) {
  const obj = {};
  Object.setPrototypeOf(obj, constructor.prototype);
  return constructor.call(obj, ...args) || obj;
}

Enter fullscreen mode Exit fullscreen mode

How spawn works

Since new returns an object, we first create a fresh object each time for a call of spawn and set its prototype.

Now we call the constructor by setting its this argument to the fresh object . After this call all the properties in the constructor function will be assigned (for eg: name, age)

Then we check to see if the constructor returns anything and we respect that , so we return whatever it returns (In most cases constructor doesn't return anything and we return the object)

Thanks for reading
Don't forget to ❤️ it :)
And follow me for more cool stuff

Top comments (0)