JavaScript – Prototype Pattern

GitHub Code

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.

To run:

  • Make GET Call

Screen Shot 2017-04-29 at 10.19.09 PM

  • View Results

Screen Shot 2017-04-29 at 10.20.02 PM

This sample is made up of three files – createObject.js, Object.js and prototypeDriver.js

Screen Shot 2017-04-29 at 10.19.29 PM

Specifics:

  • 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.

Screen Shot 2017-04-29 at 10.37.39 PM

  • Object.js – The object definition.

Screen Shot 2017-04-29 at 10.18.47 PM

  • prototypeDriver.js – A driver module like all of the other patterns.

Screen Shot 2017-04-29 at 10.18.30 PM

Stay tuned!

References
1.    http://www.blackwasp.co.uk/Prototype.aspx

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s