How can I check if an anonymous object that was created as such:
var myObj = { prop1: 'no', prop2: function () { return false; } }
does indeed have a prop2 defined?
prop2
will always be defined as a function, but for some objects it is not required and will not be defined.
I tried what was suggested here: How to determine if Native JavaScript Object has a Property/Method? but I don't think it works for anonymous objects .
Use the typeof operator to check if an object contains a function, e.g. typeof obj. sum === 'function' . The typeof operator returns a string that indicates the type of the value.
The hasOwnProperty() method will check if an object contains a direct property and will return true or false if it exists or not. The hasOwnProperty() method will only return true for direct properties and not inherited properties from the prototype chain.
typeof myObj.prop2 === 'function';
will let you know if the function is defined.
if(typeof myObj.prop2 === 'function') { alert("It's a function"); } else if (typeof myObj.prop2 === 'undefined') { alert("It's undefined"); } else { alert("It's neither undefined nor a function. It's a " + typeof myObj.prop2); }
You want hasOwnProperty()
:
var myObj1 = { prop1: 'no', prop2: function () { return false; } } var myObj2 = { prop1: 'no' } console.log(myObj1.hasOwnProperty('prop2')); // returns true console.log(myObj2.hasOwnProperty('prop2')); // returns false
References: Mozilla, Microsoft, phrogz.net.
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