What’s “new” in JavaScript?
Few syntactic features highlight JavaScript’s object oriented nature more than the new
operator. Many of us have been using it for years but do we really know what it does? In languages like Java it allocates memory for an instance object, invokes a constructor function, and returns a reference to the object. And the same holds for JavaScript. But with the language’s use of first class functions and prototypal inheritance, there’s much more to new
.
In this post I’ll cover the relationship between function instance objects, prototype objects and instance objects, what happens when new
invokes functions, and which functions can be used as constructors.
Function Instances & Prototypes
Before we explore how new
works let’s quickly review JavaScript functions. When a function is defined a function instance object is created under the hood, having a prototype property that...