Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

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

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();
Enter fullscreen modeExit 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:

constclient=spawn(Person,'Vladimir',32);
Enter fullscreen modeExit fullscreen mode

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;}
Enter fullscreen modeExit 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 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)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

  • Education
    StackOverflow
  • Work
    Help people!
  • Joined

More fromTilak Madichetti

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp