I have been studying JavaScript a bit lately and thought I would take some time to post on the power of prototype-based programming. JavaScript is an object-oriented language, but uses prototypes rather than classes to achieve this. It can be a little confusing for those coming from a traditional objected-oriented language and many JavaScript frameworks offer more familiar interfaces for dealing with the difference.
To demonstrate some of the interesting aspects of prototype-based programming in JavaScript, I thought I would create implementations of three well known data structures: stacks, queues, and deques.
A stack is a LIFO (last in first out) data structure where elements are added and removed from the top.
A queue is a FIFO (first in first out) data structure where elements are added to the back and removed from the front. The queues functionality for adding and removing items is different than a stack’s, but the functionality for resetting and checking to see if it is empty are the same, so I was able to copy the methods from the stack implementation right over. The scope of the methods change when used in this context, so the this.items and this.length now refer to the queue’s properties rather than the stack’s.
A deque is a combination of a stack and a queue. Elements may be added and removed from either the front or back of the data structure. Since this data structure’s functionality is fully implemented by the stack and queue code above, I was able to simple “inherit” the methods from these data structures and not worry about creating any new code.
If you are like me, JavaScript seemed like a quirky language that was hard to use and understand and was only useful for some client-side processing on web pages. The trend in perception has been slowly changing over the past few years thanks to web applications that rely heavily on JavaScript for functionality and now new server side software like CouchDB and Node.js that use JavaScript on the server (CouchDB using SpiderMonkey for views and Node.js using Google’s V8 to provide an evented framework for building web applications in JavaScript.)





