How to check if anonymous object has a method?

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.

Tags:

Javascript