Home JavaScript OOP - Prototyping Encapsulation and Inheritance

JavaScript OOP - Prototyping Encapsulation and Inheritance

JavaScript is a really cool language. Its flexibility allows a clever developer to achieve some incredible things. However, this unbridled freedom comes at a price. It is the responsibility of the programmer to impose order to this chaotic environment. A good first step in this daunting challenge is to implement some useful object oriented concepts. This post demonstrates how to implement encapsulation and inheritance for javascript prototype classes.


The fundamental goal for encapsulation is to control what variables/functions are available for external access. The mechanism for doing this in JavaScript is a closure. By wrapping the class definition in a closure it is possible to have private functions accesible only this class, since objects outside of the closure won't be in the same scope.


window.JSObject = function(){
this.publicInstanceVar1 = 1

// public function
JSObject.prototype.foo = function(){
privateFunction.apply(this); //call private function

//private function
function bar(){}

var privateClassVar1 = "1"


The constructor must be attached to the window, or declared outside of the closure, otherwise it will not be accessible externally. The public method is added to the object prototype. The private method is a function declared inside of the closure and must be called using apply or call to maintain the consistency the this variable.


Inheritance for a prototype object is very simple. Assigning a new parent object to the prototype of the inheriting object will do the trick.

window.Child = function(){};
Child.prototype = new Parent();

The instance variables and public functions are now available in the child class. The private methods and private class variables will not be inherited.

Click Here to see a demo.