Prototypal Inheritance

In 2006, Douglas Crockford wrote an article entitled " Prototypal Inheritance in JavaScript " in which he introduced a method of inheritance that didn't involve the use of strictly defined constructors. His premise was that prototypes allow you to create new objects based on existing objects without the need for defining custom types. The function he introduced to this end is as follows:


The object() function creates a temporary constructor, assigns a given object as the constructor's prototype, and returns a new instance of the temporary type. Essentially, object() performs a shadow copy of any object that is passed into it.

This is the way Crockford advocates using prototypal inheritance: You have an object that you want to use as the base of another object. That object should be passed into object(), and the resulting object should be modified accordingly. In this example, the person object contains information that should be available on another object, so it is passed into the object() function, which returns a new object. The new object has person as its prototype, meaning that it has both a primitive value property and a reference value property on its prototype. This also means that person.friends is shared not only by person , but also with anotherPerson and yetAnotherPerson . Effectively, this code has created two clones of person . Prototypal inheritance is useful when there is no need for the overhead of creating separate constructors but you still need an object to behave similarly to another. Keep in mind that properties containing reference values will always share those values, similar to using the prototype pattern.