views:

110

answers:

4

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: http://stackoverflow.com/questions/595766/how-to-determine-if-native-javascript-object-has-a-property-method but I don't think it works for anonymous objects .

+5  A: 

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);
}
Sean Vieira
+1  A: 

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

Ain
+1  A: 

What do you mean by an "anonymous object?" myObj is not anonymous since you've assigned an object literal to a variable. You can just test this:

if (typeof myObj.prop2 === 'function')
{
    // do whatever
}
Matt Ball
A: 

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

References: Mozilla, Microsoft, phrogz.net.

artlung