Did You Know?
JavaScript inner functions always have access to outer function's variables. More...

Private members in JavaScript

Posted: February 10th, 2010 | Author: diegoquinteiro | Filed under: Uncategorized | No Comments »



Encapsulation is the most important achievement of object oriented programming. Using a piece of software without worrying about its implementation makes possible for our limited brain to understand and code complex applications.

A simple example in Java:

public class Point {
    private double x;
    private double y;
    public Ponto (double x, double y) {
        this.x = x;
        this.y = y;
    }
    public double distanceFromOrigin () {
        return Math.sqrt(x * x + y * y);
    }
}

Anyone who wants to use this class doesn’t need to know how the point coordinates is stored or how the distance from the origin is calculated. The information is encapsulated. Encapsulation improves abstraction and simplifies our code.

In order to encapsulate properly, we need private members, i.e. variables that can’t be read or changed from outside our software piece.

In more traditional languages such as Java, it is done with explicit access control. By using the private keyword, we prevent the variable from being accessed outside its own class. But how can we do the same with JavaScript, since it doesn’t even have classes?

In fact, it’s very simple. Variables defined within a function are confined to the function scope. As discussed in my last post about closures, inner functions have access to their outer function’s scope. Putting it all together, we have what we want:

var Point = function (x, y) {
    this.distanceFromOrigin = function () {
        return Math.sqrt(x * x + y * y);
    }
}

var point = new Point(3, 4);
alert(point.distanceFromOrigin()); // alerts "5"

alert(point.x); // alerts "undefined"
alert(point.y); // alerts "undefined"

That way, x and y are private members. They are local variables of the constructor and would not exist outside it. When distanceFromOrigin is assigned to the this object, which is returned, a closure is created so that function will keep permanent access to that local variables.

The cost of using this technique is that with every execution of the constructor the inner functions are recreated. One instance of each method for each object instance. Usually this is not a problem at all, but watch out for objects that have hundreads or thousands of instances.



Leave a Reply