I think I might fail at Googling, and maybe this pattern just doesn’t fit with the way JavaScript handles MRO, but I’m looking for an equivalent to Perl’s AUTOLOAD method such that:
function car() {
return {
start: function() { alert('vrooom') },
catchall: function() { alert('car does not do that'); }
}
};
car().start(); //vrooom
car().growBeard(); //car does not do that
in Perl to quickly handle this situation I’d write:
sub AUTOLOAD { __PACKAGE__." doesn't do that" }
but the syntax to catch an undefined method in JavaScript eludes me.
Perhaps overloading .call or .apply or something?
If you simply want to know if a method is defined you can do the following:
It sounds like what you are looking for is
__noSuchMethod__, however it is only supported in mozilla, and not part of the formal ECMAScript specifications.Example of
__noSuchMethod__on jsfiddle, only works in a mozilla based browser.Using simple exception handling you might be able to get your desired behavior: