I'm simply trying to avoid this
if(typeof myObject !== 'undefined' && myObject !== null)
{
//safely use myObject
}
so I tried this
Object.prototype.doesExist = function() {
return (typeof this !== "undefined" && this !== null);
}
followed by
if(myObject.doesExist()){
//safely use myObject
}
but of course the result is myObject is not defined
it understand why this doesn't work, but has anybody figured out a better way to accomplish what I'm looking for?
As stated in the comments, null or undefined are not instances of an Object, so they won't inherit Object's prototype.
Solution 1: Use a static Object method, which is a functional, though not quite as clean, solution similar to what you were trying to do.
Object.exists = function(obj) {
return typeof obj !== "undefined" && obj !== null;
}
if (Object.exists(myObject)) {
// safely use myObject
}
Solution 2: Use instanceof if you know what type of object you're expecting. This is recommended if you will be accessing ClassName's interface inside your if statement.
if (myObject instanceof ClassName) {
// safely use myObject
}
Examples:
function A() {}
var a = new A(), b;
> a instanceof A
true
> a instanceof Object
true
> b instanceof A
false
> b instanceof Object
false
> null instanceof A
false
> null instanceof Object
false
> undefined instanceof A
false
> undefined instanceof Object
false
I think that handles your use-cases
Loose equality will achieve the desired result without monkey-patching although it requires some knowledge of javascript's semantics:
myObject == null; //true for null and undefined, false for all others
You can also use logical and as a guard operator:
if ((myObject != null) && myObject.someMethod && myObject.someMethod());
Obviously you could criticize the above for readability, but because javascript dumps everything into the same global namespace I'd be very careful about adding even static methods to Object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With