The Constructor Pattern
In classical object-oriented programming languages, a constructor is a special method used to initialize a newly created object once memory has been allocated for it. In JavaScript, as almost everything is an object, we’re most often interested in object constructors.
Object constructors are used to create specific types of objects—both preparing the object for use and accepting arguments a constructor can use to set the values of member properties and methods when the object is first created (Figure 9-1).

Figure 9-1. Constructor pattern
Object Creation
The two common ways to create new objects in JavaScript are as follows:
// Each of the following options will create a new empty object:varnewObject={};// or which is a shorthand for the object constructorvarnewObject=newObject();
Where the Object constructor creates an object
wrapper for a specific value, or where no value is passed, it will
create an empty object and return it.
There are then four ways in which keys and values can be assigned to an object:
// ECMAScript 3 compatible approaches// 1. Dot syntax// Set propertiesnewObject.someKey="Hello World";// Get propertiesvarkey=newObject.someKey;// 2. Square bracket syntax// Set propertiesnewObject["someKey"]="Hello World";// Get propertiesvarkey=newObject["someKey"];// ECMAScript 5 only compatible approaches// For more information ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access