How to check if anonymous object has a method?

前端 未结 6 1840
遥遥无期
遥遥无期 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: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.

提交回复
热议问题