Using closures to simulate encapsulation in Javascript

Javascript is not an object oriented programming language per se. Although everything in Javascript is an object, there is no real concept of a class construct; objects are simply a collection of key/value pairs. As a result, tenets of OOP such as classical inheritance are not really possible with the language. Instead, Javascript supports “object reuse” through prototypal inheritance. This is a different flavor of inheritance where objects clone key/value pairs from prototype objects. Encapsulation, another key tenet of object oriented programming, is also not directly supported in Javascript either. There are no “public”, “private”, or “protected” keywords.

However, it is possible to simulate private variables through closures in Javascript. A closure is simply a function defined inside another function in Javascript. The closure has access to all the local variables defined within the containing function. Note that any local variable defined within the containing function is not accessible outside said function, as it will no longer be in scope. For example:

function Foo()	
{
	var bar = 5;
}

alert(bar);

This will error, since bar is defined inside Foo, and not accessible from the global context. To get around this, we define a closure inside Foo:

function Foo()
{
	var bar = 5;

        this.IncrementBar = function (){
	    Bar++;
        }
} 

Var myFoo = new Foo();
myFoo.IncrementBar(); 

The IncrementBar() function is defined within Foo() and thus has access to the bar variable. Furthermore, because IncrementBar() is assigned to the “this” object, by instantiating an instance of Foo, the new object will now have a public method with which it can modify bar. The bar variable is local to the Foo() constructor, and hence cannot be accessed from outside. Trying to set myFoo.bar will create a new property on the foo object, but will not override the bar variable declared within Foo(), which is no longer in scope. bar is for all intents and purposes, “private” to the foo object. While using closures is not quite as easy as slapping on a private keyword in front of bar, it achieves the same effect.

Leave a Reply

Your email address will not be published. Required fields are marked *