« October 2005 »
SunMonTueWedThuFriSat
      
1
2
3
4
8
9
10
11
12
13
15
16
17
19
22
23
27
28
30
31
     
Today
XML

Blog::Navigation

GetJava Download Button
Get the Source
Personal Blog

Blog::Referers

Today's Page Hits: 722

Powered by Roller Weblogger.
« Previous day (Oct 27, 2005) | Main | Next day (Oct 29, 2005) »
20051029 Saturday October 29, 2005

doesNotUnderstand in JavaScript?

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")




( Oct 29 2005, 07:44:29 PM IST ) Permalink del.icio.us | furl | simpy | slashdot | technorati | digg

Copyright (C) 2005, A. Sundararajan's Weblog