Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if anonymous object has a method?

Tags:

javascript

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 .

like image 902
Omar Avatar asked Jun 09 '10 15:06

Omar


People also ask

How do you check if an object has a method in JavaScript?

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.

How do you check if an object contains a property?

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.


2 Answers

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); } 
like image 65
Sean Vieira Avatar answered Sep 23 '22 02:09

Sean Vieira


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.

like image 23
artlung Avatar answered Sep 24 '22 02:09

artlung