How to check if anonymous object has a method?

前端 未结 6 1824
遥遥无期
遥遥无期 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条回答
  •  梦毁少年i
    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

提交回复
热议问题