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


Comments:

Post a Comment:
Comments are closed for this entry.
About

sundararajan

Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today
Bookmarks
Links

No bookmarks in folder

Blogroll

No bookmarks in folder

News

No bookmarks in folder