Can I define a "fallback" method in JavaScript?

Is it possible (at my own discretion) to define "fallback" methods in JavaScript?

for instance

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 

Ie: I want defaultMethod to defaultMethod called whenever I write obj.calledMethod (); and obj.calledMethod == undefined , but I don't want to check for undefined in the calling code.

+4
source share
1 answer

JavaScript does not currently have this feature. This may happen in the next version, but through proxies . So before that you had to do something rather ugly, for example:

 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 as follows:

 var obj = new MyObject(); obj.ex("doesntExistInMyObject", "arg", "arg"); 

( ex for "execute" since call too easy to confuse with Function#call .)

+4
source

Source: https://habr.com/ru/post/1414611/


All Articles