Class Declarations as a Transformation of Closures

In JavaScript, one can go about creating objects with private state by hiding it in a closure made at object creation time. Something along the lines of:

var myObject = (function() {

    var privateVariable = ...;

    return {
        publicGetter:function() { return privateVariable; }
    }
})();

Here, shielding the private state occurs at execution time; that is, it’s a result of the execution of the program.

Here’s the equivalent in using class declarations in ActionScript:

class MyClass {
    private var privateVariable = ...;
    public function publicGetter():* { return privateVariable; }
}

Here we can take the “declarations” part of “class declaration” literally: The private state is now private because it’s declared that way, rather than as a side effect of program execution.

Thus, class declarations provide a declarative transform of one particular thing that can be achieved via closures. As a mechanism, closures are of course more powerful and widely applicable. For purposes of writing and reading maintainable code, it’s preferable to have declarative support for common patterns like this.

Comments are closed.