views:

109

answers:

3

Is there a way to specify something similar to the following in javascript?

var c = {};
c.a = function() { }

c.__call__ = function (function_name, args) {
    c[function_name] = function () { }; //it doesn't have to capture c... we can also have the obj passed in
    return c[function_name](args);
}

c.a(); //calls c.a() directly
c.b(); //goes into c.__call__ because c.b() doesn't exist
+1  A: 

No.

Vilx-
+5  A: 

Mozilla implements noSuchMethod but otherwise...no.

MooGoo
+2  A: 

No, not really. There are some alternatives - though not as nice or convenient as your example.

For example:

function MethodManager(object) {
   var methods = {};

   this.defineMethod = function (methodName, func) {
       methods[methodName] = func;
   };

   this.call = function (methodName, args, thisp) {
       var method = methods[methodName] = methods[methodName] || function () {};
       return methods[methodName].apply(thisp || object, args);
   };
}

var obj = new MethodManager({});
obj.defineMethod('hello', function (name) { console.log("hello " + name); });
obj.call('hello', ['world']);
// "hello world"
obj.call('dne');
CD Sanchez