2

I'm trying to emulate an object that has a number of methods in JSBin. I don't want to redefine the entire method is JSBin. Mostly because methods are being added frequently and I'm just trying to explore if what I want is even possible. Is there a way that I could create an object so that whatever method was called on it, it would just return an arbitrary value?

var ret = {

  //no methods

};

var result = ret.getSomeVal("funny_cat.gif");

console.log(result); //funny_cat.gif

Could something intercept this call to ret and create the returnSomeVal method automatically, so that it would just return whatever argument was passed to it?

1252748
  • 12,116
  • 27
  • 89
  • 197

2 Answers2

1

In Ruby, this feature is called method_missing. It's a method that gets called whenever you call a method that hasn't been defined on an object.

From then on, you can do whatever you want, like send yourself an e-mail to notify you that some user tried to call an undefined method or even make method_missing return some default response in those cases.

I found this port of method_missing to javascript. It looks like what you're after:

https://github.com/nakajima/method-missing-js

Felipe
  • 10,031
  • 7
  • 45
  • 97
1

Proxies were designed to allow catch-alls like this.

Proxies are objects for which the programmer has to define the semantics in JavaScript.

So you can redefine obj[...] to return a default value for undefined properties instead of undefined. They're a planned API for EcmaScript.next so are not yet standardized though a lot of browsers have been implementing them as the spec is finalized.

The simple example returns 37 for any

var handler = {
    get: function(target, name){
        return name in target?
            target[name] :
            37;
    }
};

var p = new Proxy({}, handler);

You can modify this to return a method instead.

function returns_37() { return 37; }

var handler = {
    get: function(target, name){
        return name in target?
            target[name] :
            returns_37;
    }
};

var p = new Proxy({}, handler);
Community
  • 1
  • 1
Mike Samuel
  • 109,453
  • 27
  • 204
  • 234