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.