I'm sure this has definitively been answered before, and I've tried to search for it.. maybe my search terms are wrong...
Basically I have an object myObject, and I have a set of defined properties and methods for it. What I want to do is be able to handle calls/references to properties and methods that I have not defined.
For example, let's say I have this:
var myObject = {
someProperty : 'foobar',
someFunction : function () { /* Do stuff */ }
}
Currently, if someone tries to make a call to myObject.someOtherFunction(), JavaScript yells and screams about it. What I want to do is setup a way to automatically handle that. So for example, instead of JavaScript throwing an error, my object just returns false. Is this possible?
Another way to look at it is this:
var myObject = {
someFunction : function () { /* Do stuff */ }
magicBucket : function () { /* Do stuff */ }
}
If I call myObject.someFunction(), well that is defined and does something. What I want to happen is if I were to for instance call myObject.someOtherFunction(), instead of JavaScript throwing an error, it would call myObject.magicBucket().
The reason is that I have a client that uses a third-party library on their site. They want to discontinue using it, but completely removing it is going to take a lot of time and effort. So as a short-term solution, they wanted to know if I could make a dummy file that basically does nothing. Well, this library uses several objects that has lots of methods. I could go through everything and make dummy objects, but I thought maybe there might be some easy "catch-all" method to do this.
Some have mentioned checking if the method exists first, wrapping it in a condition or try..catch, etc. Well, the point of this is that at this time I can't touch the actual calls to the methods. And since the overall goal is to eventually remove the coding altogether, it's not even applicable.
someOtherFunctionwill either beundefinedor a function, you could domyObject.someOtherFunction?myObject.someOtherFunction():false, so you only invokemyObject.someOtherFunctionif it is not a "falsy" value (falseundefined,null,0), or yieldfalseas a fallback value.try/catchblocks or for checking if the desired function/property exists on the object. If someone other than you is using your code, then you cannot be entirely responsible for them trying to use a potentially nonexistent property. Are you encountering a situation where your object may or may not havesomeOtherFunctionon it, and you want to handle the situation if it does or does not have it?for (var mthd in myObject) { if (typeof mthd == 'function') {to programmatically generate a list of methods to be dummies. (I program quick'ndirty scripts to generate scripts all the time, scriptception basically)