Practical Object Oriented Javascript from Web Dev Conference

Earlier this year, I attended the Practical Object Oriented Javascript workshop at Web Dev Conference in Chicago.  The developers from DevMynd showcased their strategies and approaches for creating complex applications with Javascript.  It was a insightful presentation and I am going to share the main point from their presentation: utilizing the object oriented class approach within Javascript.

Let’s step back into some of the basics of Javascript.

Objects are one of the basic building blocks of Javascript.  New objects are created easily and often.

Code1

Adding functions to an object is simple and they are called methods when a property of an object.

code2

When discussing objects inside of Javascript, a traditional “Class” model is missing. Instead, we utilize “this” and “new” to create our own version of this OO feature. By creating a constructor function and then invoking the “new” keyword, a new instance of the object is created. Here is an example of a constructor function and invoking it.

Code3

Ensure that you utilize the “new” keyword, otherwise unintended consequences will occur including properties leaking to the global scope.

To add methods to this class, a function is assigned to the prototype of the class. The prototype stores all methods associated with a class.

Code4

Do not add the function declaration inside of the class constructor as seen below.

Code5

This causes a new instance of this function to be created every time the constructor is called, instead of reusing the function. Make sure that the prototype method discussed earlier is being used. Using this method makes it extremely easy to apply a testing framework to the Javascript. I would heavily recommend utilizing test driven development with this approach. Creating a test that fails and then creating a method to attach to the class to make it pass is an excellent approach for development. This approach hopefully causes people to rethink how simple Javascript objects and created.

To view the presentation from DevMynd, please see the GitHub page.  Most of the code snippets are taken from their presentation.

Clayton

Written by Clayton

Leave a Reply

*