Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
77
rated 0 times [  82] [ 5]  / answers: 1 / hits: 176309  / 14 Years ago, wed, june 9, 2010, 12:00:00

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 .


More From » javascript

 Answers
53

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);
}

[#96550] Saturday, June 5, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
charity

Total Points: 503
Total Questions: 98
Total Answers: 125

Location: Mali
Member since Fri, Dec 3, 2021
3 Years ago
;