The Prototype pattern enables cloning of an existing object into another. This is not what I was expecting when I first read the name. As I understand it, there is one object definition with instances representing the differences. More specifically, a car is the object definition and each ‘instance’ represents a separate and independant car out in the world. For example, say 5 sedans are sold. As each sedan is sold, it is ‘created’ by cloning the previous one and changing the owner’s name, address and other data points appropriately.
Before I go into detail, I discovered something interesting. Normally in C# and other more traditional strongly typed Object Oriented (OO) languages, I have been able to have a clone method inside a class definition and create a new instance of that class. However, I tried doing that with the Object.create() method inside the Object clone definition and I kept getting a Object.create is not a function. To get around this, I create a separate create method and referenced it inside the clone.
- Make GET Call
- View Results
This sample is made up of three files – createObject.js, Object.js and prototypeDriver.js
- createObject.js – This file exists solely because of the above mentioned ‘Object.create is not a function’. It is called in the clone method object Object.js and in the initial object creation inside prototypeDriver.js.
- Object.js – The object definition.
- prototypeDriver.js – A driver module like all of the other patterns.