How to check if anonymous object has a method?

前端 未结 6 1819
遥遥无期
遥遥无期 2020-12-23 20:15

How can I check if an anonymous object that was created as such:

var myObj = { 
    prop1: \'no\',
    prop2: function () { return false; }
}
相关标签:
6条回答
  • 2020-12-23 20:27

    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
    0 讨论(0)
  • 2020-12-23 20:27

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

    0 讨论(0)
  • 2020-12-23 20:28

    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);
    }
    
    0 讨论(0)
  • 2020-12-23 20:29

    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.

    0 讨论(0)
  • 2020-12-23 20:30

    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
    }
    
    0 讨论(0)
  • 2020-12-23 20:31

    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:

    myObj.prop2
    

    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>
    
    0 讨论(0)
提交回复
热议问题