5

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

4 Answers 4

7

Mozilla implements noSuchMethod but otherwise...no.

Sign up to request clarification or add additional context in comments.

Comments

6

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');

Comments

2

Almost 6 years later and there's finally a way, using Proxy:

const c = new Proxy({}, {
  get (target, key) {
    if (key in target) return target[key];

    return function () {
      console.log(`invoked ${key}() from proxy`);
    };
  }
});

c.a = function () {
  console.log('invoked a()');
};

c.a();
c.b();

Comments

1

No.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.