How to check if an anonymous object has a method?

How to check if an anonymous object was created this way:

var myObj = { prop1: 'no', prop2: function () { return false; } } 

really has 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 a native JavaScript object has a Property / Method? but I don’t think it works for anonymous objects.

+133
javascript
Jun 09 '10 at 15:45
source share
5 answers

typeof myObj.prop2 === 'function'; will tell you if the function is defined.

 if(typeof myObj.prop2 === 'function') { alert("It a function"); } else if (typeof myObj.prop2 === 'undefined') { alert("It undefined"); } else { alert("It neither undefined nor a function. It a " + typeof myObj.prop2); } 
+251
Jun 09 '10 at 15:48
source share

Do you want hasOwnProperty() :

 var myObj1 = { prop1: 'no', prop2: function () { return false; } } var myObj2 = { prop1: 'no' } alert(myObj1.hasOwnProperty('prop2')); // returns true alert(myObj2.hasOwnProperty('prop2')); // returns false 

Links: Mozilla , Microsoft , phrogz.net .

+38
Jun 09 '10 at 16:34
source share

3 Options

  • typeof myObj.prop2 === 'function' if the property name is not dynamic / generated
  • myObj.hasOwnProperty('prop2') if the property name is dynamic and checks to see if it is a direct property (and not a prototype chain).
  • 'prop2' in myObj if the property name is dynamic and check the prototype chain
+13
Dec 07 '16 at 1:55
source share

What do you mean by an anonymous object? myObj not anonymous since you assigned an object literal to a variable. You can simply check this:

 if (typeof myObj.prop2 === 'function') { // do whatever } 
+8
Jun 09 '10 at 15:50
source share

One way to do this would be if (typeof myObj.prop1 != "undefined") {...}

+1
Jun 09 '10 at 15:49
source share



All Articles