Can I define a "fallback" method in JavaScript?
javascript
Solution
JavaScript doesn't currently have that feature. It may well in the next version, though, via proxies. So until then, to do this you'd have to do something fairly ugly, like:
MyObject.prototype.ex = function(fname) {
var f = this[fname],
args = Array.prototype.slice.call(arguments, 1);
if (typeof f === "function") {
return f.apply(this, args);
}
return this.defaultMethod.apply(this, args);
};
...and use it like this:
var obj = new MyObject();
obj.ex("doesntExistInMyObject", "arg", "arg");
(`ex` for "execute", since `call` is too easily confused with `Function#call`.)
Problem
Is it (in a performant way) possible to define "fallback" methods in JavaScript? For example ``` function MyObject () { /* what do i have to add here to have my defaultMethod? */ } var obj = new MyObject (); obj.doesntExistInMyObject (); // I want defaultMethod to be called obj.doesntExistEither (); // I want defaultMethod to be called, too ``` I.e.: I want `defaultMethod` to be called whenever I write `obj.calledMethod ();` and `obj.calledMethod == undefined`, but I do not want to check for `undefined` in the calling code.