Rather than having to check whether an object is defined or not, I’d like to be able to simply call a method on it and have it fail silently if the object is in fact undefined. So, rather than having to write the following:
if(obj.delegate && obj.delegate.closeMenu){
obj.delegate.closeMenu();
}
I could just write the line inside the if statement: obj.delegate.closeMenu(). If obj has no delegate property, simply nothing would happen. Same thing if delegate does exist, but it has no closeMenu() method.
Is this possible? If so, please offer an implementation.
There’s currently no reliable way to do this, without writing more code. You could use
try–catch, for example:Note that the non-standard
__noSuchMethod__does what you want, although it’s not supported everywhere.Update: In ES6, you could use a proxy to do something similar. For example: