JavaScript is lot similar to Self Programming Language. Similarities include:
// 'b' property is accessed by get accessor method
var d = { get b() { return "hello"; } }
alert(d.b); // calls function defined above
// explicit accessor method set for property "f"
d.__defineGetter__("f", function() { return 23 * 2} );
alert(d.f); // calls function set in __defineGetter__
But, Mustang includes Rhino JavaScript engine and therefore does not support getters and setters. But, we have added global constructor called JSAdapter. This is more flexible than the
getters and setters. JSAdapter accepts an object with specially named methods: __get__, __has__, __put__, __delete__
and __getIds__
var y = {
__get__ : function (name) { ... }
__has__ : function (name) { ... }
__put__ : function (name, value) {...}
__delete__ : function (name) { ... }
__getIds__ : function () { ... }
};
var x = new JSAdapter(y);
x.i; // calls y.__get__
i in x; // calls y.__has__
x.p = 10; // calls y.__put__
delete x.p; // calls y.__delete__
for (i in x) { print(i); } // calls y.__getIds__
Note that JSAdapter may also be created using Java anonymous class-like syntax:
var x = new JSAdapter() {
__get__ : function (name) { ... }
__has__ : function (name) { ... }
__put__ : function (name, value) {...}
__delete__ : function (name) { ... }
__getIds__ : function () { ... }
};
The caller/user of the adapter object is isolated from the fact that the property accesses/mutations/deletions are really calls to JavaScript methods on adaptee. Use cases include 'smart' properties, property access tracing/debugging, encaptulation with easy client access - in short JavaScript becomes more "Self" like. In fact, we have used JSAdapter feature in Object Query Language (OQL) implementation.
Note that Rhino already supports special properties like __proto__ (to set, get prototype), __parent__ (to set, get parent scope). We follow the same double underscore nameing convention here for special methods for JSAdapter.
Posted by darrel karisch on January 23, 2007 at 05:11 AM IST #