Tuesday, May 27, 2008

Douglas Crockford: Durable Objects

Fortunately, JavaScript provides the means to construct durable objects that can perfectly guard their state by using a variation of the Module Pattern.
...
By adding one simple rule, we can easily generate secure objects:
A durable object contains no visible data members, and its methods use neither this nor that.

This is a template for a durable constructor:

function durable(parameters) {
var that = {} or the product of another durable constructor;

var private variables;

function method() {

}

that.method = method;
return that;
}

Define all of your methods as private methods. The methods you choose to expose to the public get copied into that. None of the functions defined or inherited make use of that or this.
...
Durable objects allow code from multiple (possibly untrusted) parties to
cooperate. Durable objects can be expressed in a safe subset of JavaScript,
such as ADsafe or Cajita.