When a method is called on a SmallTalk object, the methods associated with that object's class and its superclasses are searched at runtime. If none of these classes implement a method of given name, the Smalltalk virtual machine calls doesNotUnderstand (see also Reflective Facilities in SmallTalk) method on the object. How about this facility for JavaScript? We can easily implement such a feature for JavaScript engine in Mustang. We can use JSAdapter feature.
function Wrapper(obj) {
return new JSAdapter() {
__has__ : function(name) {
// this object supports property or method of any name
return true;
},
__get__ : function(name) {
// check whether wrapped object supports given
// member (field or method).
if (name in obj) {
return obj[name];
} else if (typeof(obj["doesNotUnderstand"]) == 'function') {
// if object has 'doesNotUnderstand' method, then
// return a function that would call it
return function() {
return obj.doesNotUnderstand(name, arguments);
}
} else {
// unsupported
return undefined;
}
}
};
}
Code that uses could look like:
var v = {
a : 10,
toString: function() { return "I am v"; },
doesNotUnderstand: function(name) {
print(name + " called");
}
};
var x = Wrapper(v);
x.a; // This is same as v.a which is 10
x.toString(); // This is same as v.toString()
x.func(); // calls v.doesNotUnderstand("func")