Javascript - Creating Instances with new
Code Life
By Pierre Marsaa
What new Actually Does
Think of a class as a rubber stamp and of each object as one print made with it. The keyword that presses the stamp is new.
If you forget new and call the class like a regular function, JavaScript refuses to build anything and throws a TypeError:
↗️
Loading editor...
↶
↷
An object built from a class is called an instance of that class: zap is an instance of Codemon.
Behind the scenes, new Codemon("Zap") does three things in a row:
1.
Creates a brand-new empty object.
2.
Runs the constructor with this pointing at that object, so this.name = name fills it in.
3.
Returns the finished object, which you store in zap.
Verify