I have code that looks like this:
obj.foo(); // obj might, or might not have a `foo` method.
I want to know if I can override what happens when obj.foo is called in my code, for example:
obj.foo = function(){ alert ("Hello"); });
obj.onCallNonExistentMethod = function(){ // I know this is imaginary syntax
alert("World");
}
obj.foo(); // alerts "Hello"
delete obj.foo;
obj.foo(); // alerts "World" , would TypeError without the method missing handler.
From what I understand, in Ruby that would be method_missing or const_missing or something similar.
Can I override what happens on a call to a nonexistent object method in JavaScript? If I can, how do I do it?
The goal is to validate an API I provide to users so they can use the API safely and I can warn them more clearly on errors.
Unfortunately that’s not possible in any widely supported way. The closest you can get is using a proxy function for all calls, i.e. instead of
foo.bar()you would use something likefoo.invoke('bar'). However, that’s pretty ugly and most likely close to what you meant in the first “not interested in” part.In loosely-typed languages is is pretty common to expect the developer to pass compatible objects though – i.e. getting an error when passing something unexpected is usually fine.
However, if you are lucky enough to use a JS engine which supports ECMAScript-harmony features (obviously IE doesn’t), you can use Proxy objects to achieve this. Basically you wrap your object in a Proxy which lets you trap most operations on the object such as iterating it, retrieving a property, or even creating properties. Besides the two links having a look at this answer to this question might be worth a shot.