
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
functionPerson(name,age){this.name=name;this.age=age;}Person.prototype.describe=function(){console.log(`I am${this.name} ,${this.age} years of age ! `);}constclient=newPerson('Vladimir',32);client.describe();
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:
constclient=spawn(Person,'Vladimir',32);
wherespawn
is our own function that we create which should substitutenew
functionspawn(constructor,...args){constobj={};Object.setPrototypeOf(obj,constructor.prototype);returnconstructor.call(obj,...args)||obj;}
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 itsthis
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)
For further actions, you may consider blocking this person and/orreporting abuse