A Slightly Deeper Dive Into Object Oriented Programming with JavaScript

Terungwa Kombol
3 min readMar 13, 2017

--

There are three common ways of implementing object oriented programming in JavaScript. The reason JavaScript has such flexibility is due to its prototypal nature.

Pseudoclassical

This pattern tries to mimic the classical pattern of implementing object oriented programming that is common to most languages. It uses the function constructor to create a base class that all objects can inherit from. Instances of the class must be created by invoking the function with the new operator. The main disadvantage I discovered was that it was difficult to make data truly private. Also there is no access to super methods ( methods of the base class), hence it will be difficult to implement polymorphism.

Prototypal

This pattern makes true use of JavaScript’s prototypal nature. Here objects inherit from other objects. Once an initial object is created, we can create more instances of the object using the Object.create method. New instances can be customized with additional methods and/or properties. This pattern still has the problem of no privacy.

Functional

The pattern I have used for my task is the Functional pattern of object oriented programming implementation in JavaScript. First, I start by making a function — footballPlayer — that will return objects. I define internal private variables. This is possible because of closures: variables defined in a function have scope only within that function. Thus it can only be accessed by anything within the function. In this function, I create an object called ‘that’. This is the value that will be returned by this function. The objects properties and methods are defined. These properties perform different tasks including accessing private data, since they are within the scope of the function.

Next, I create a goalkeeper function that inherits from the footballPlayer class by invoking it within its scope. My new object will be customized with its own properties. Here I implement polymorphism by creating another method player_action in goalkeeper class that performs an action in addition to the one it already performs in footballPlayer class.

I was able to achieve polymorphism by first augmenting Object.prototype with a method called method. This makes the method method available to all objects. What this method does is to create new function with the name in its argument and give it the prototype of the invoking object ( in this case Object() object).

Armed with the above method, I create a method called superior, which returns a function with a given name that already exists.

I can now use superior to get player_action method from the footballPlayer class, and modify it in goalkeeper class. We have the same function performing slightly different task in a different context.

--

--