Definition

Not confused with JavaScript's inheritance and prototype chain, the Prototype Pattern is used to instantiate new objects by copying all of the properties of an existing object, creating an independent clone. Therefore, it is a "creational" design pattern.

Prototype Design Pattern was introduced in the famous GoF book; "Design Patterns: Elements of Reusable Object-Oriented Software".

Classical languages such as Java and C# don't utilize this pattern much. However, because JavaScript is prototypal or prototype-oriented language, the pattern is heavily used, especially in the construction of new objects.

Use Cases

The Prototype pattern is particularly useful when the construction of a new object directly is inefficient and expensive.

Some of the cases for using this pattern are:

  • Initializing an object goes through multiple long and performance killer processes such as sending multiple AJAX requests to an API.

  • Having to perform some operations on a large scale object or array in an object in order to use that object.

  • In Node.js environment for example, when performing a comprehensive database operation to create an object.

For those cases (and more), if another process needs to use this object, it would be convenient and practical to clone that object instead of creating a new one.

Example

I'm going to use Addy Osmani's example from his book: "Learning JavaScript Design Patterns".

var myCar = {
 
  name: "Ford Escort",
 
  drive: function () {
    console.log( "Weeee. I'm driving!" );
  },
 
  panic: function () {
    console.log( "Wait. How do you stop this thing?" );
  }
 
};
 
// Use Object.create to instantiate a new car
var yourCar = Object.create( myCar );
 
// Now we can see that one is a prototype of the other
console.log( yourCar.name );

For those interested, real prototypal inheritance, as defined in the ECMAScript 5 standard, requires the use of Object.create ... To remind ourselves, Object.create creates an object which has a specified prototype and optionally contains specified properties as well (e.g Object.create( prototype, optionalDescriptorObjects )).
Object.create also allows us to easily implement advanced concepts such as differential inheritance where objects are able to directly inherit from other objects.

The name property is not actually being copied to the yourCar object. It is only on myCar object where JavaScript goes and get it from because yourCar object is prototype-linked to myCar object.

When most of the JavaScript developers would call this mechanism "inheritance," others would call it “behavior delegation.” The difference is that we intentionally design our linked objects to be able to delegate from one to the other for parts of the needed behavior. But that's a subject for another article.