How to check if anonymous object has a method?

前端 未结 6 1820
遥遥无期
遥遥无期 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: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) {
      
    }
    

    Or in an expression:

    myObj.prop2 ?  : 
    

提交回复
热议问题