How to check if anonymous object has a method?

2020/11/12 00:42 · javascript ·  · 0评论

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 .

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,

3 Options

  1. typeof myObj.prop2 === 'function' if the property name is not dynamic/generated
  2. myObj.hasOwnProperty('prop2') if the property name is dynamic, and only check if it is direct property (not down the prototype chain)
  3. 'prop2' in myObj if the property name is dynamic, and check down the prototype chain

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

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

I know this is an old question, but I am surprised that all answers ensure that the method exists and it is a function, when the OP does only want to check for existence. To know it is a function (as many have stated) you may use:

typeof myObj.prop2 === 'function'

But you may also use as a condition:

typeof myObj.prop2

Or even:


This is so because a function evaluates to true and undefined evaluates to false. So if you know that if the member exists it may only be a function, you can use:

if(myObj.prop2) {
  <we have prop2>

Or in an expression:

myObj.prop2 ? <exists computation> : <no prop2 computation>
版权声明:本文为原创文章,版权归 javascript 所有,欢迎分享本文,转载请保留出处!