What's the correct way to test for existence of a property on a JavaScript Object?

前端 未结 3 535
误落风尘
误落风尘 2021-01-03 20:00

I have a custom Javascript object that I create with new, and assign properties to based on creation arguments:

function MyObject(argument) {
           


        
3条回答
  •  我在风中等你
    2021-01-03 20:11

    hasOwnProperty is exactly what you're looking for, since you specify "if the property is explicitly defined for this object, not in the prototype chain". Per https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Object/hasOwnProperty , "This method can be used to determine whether an object has the specified property as a direct property of that object; unlike the in operator, this method does not check down the object's prototype chain." -- seems to exactly match your requirement!

提交回复
热议问题