[General] Encapsulation in LK

Mark Miller erights at gmail.com
Sun May 3 20:13:54 CEST 2009


On Sun, May 3, 2009 at 7:58 AM, Owen Densmore <owen at backspaces.net> wrote:
> I'm just getting my head around JS fine points, so this could be way
> off!

You have this exactly right. JavaScript has only one working
encapsulation mechanism. This pattern of using it for defining
encapsulated objects is due to Doug Crockford (cc'ed) and is known as
the "objects as closures" pattern.

> But I believe for private method/class variables, you'd use a
> closure during the object construction (new).
>
> This closure would have "var" variables, in addition to the "this"
> variables. ?These variables would only be visible to methods, and
> could not be retrieved directly via the dot notation.

Actually, in the objects as closure pattern, "this" and "new" are both
useless. ("new"@least is also harmless. Not so for "this".) For
example:

  function Point(x, y) {
    var magnitude = Math.sqrt(x*x + y*y);
    var self = {
      getX: function(){ return x; },
      getY: function(){ return y; },
      getSize: function(){ return magnitude; },
      toString: function() {
        return '<' + self.getX() + ',' + self.getY() + '>';
      }
    }

Such an object is just a record of methods, each of which is a closure
defined in the object's construction context. The captured lexical
variables from that construction context are the object's instance
variables (x, y, magnitude, self). As Dan will remember, this view of
objects hearkens back to some of the early thinking around
Smalltalk-72 and Actors (though Smalltalk-72 had dynamic scoping).
Further elaborations of this pattern (See the Cajita examples in
<http://google-caja.googlecode.com/files/caja-spec-2008-06-07.pdf>)
can accommodate inheritance, and, on Caja and the upcoming EcmaScript
5, can make these objects tamper proof (via freezing). The
objects-as-closure pattern will also be the basis for the class system
of EcmaScript Harmony (which is likely to become EcmaScript 6).

The problem with this pattern today is that is costs one allocation
per method per instance. In previous conversations with Lively Kernel
folks, this cost was felt to be a show stopper for use of this pattern
in LK. AFAIK, no other workable technique for encapsulation has yet
been discovered for JavaScript.

-- 
Text by me above is hereby placed in the public domain

    Cheers,
    --MarkM





More information about the lively-kernel mailing list