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

前端 未结 3 507
误落风尘
误落风尘 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!

    0 讨论(0)
  • 2021-01-03 20:18

    You can check the existence of a variable as follows:

    if ( typeof variable === 'undefined' || variable === null ) {
        // Do stuff
    }
    

    It's also can be used for properties.

    0 讨论(0)
  • 2021-01-03 20:20

    If you are looking for a property defined in an object, you can use hasOwnProperty method of the object. like this:

    myObject = new MyObject();
    // some code
    if ( myObject.hasOwnProperty('prop') ) {
        // prop exists
    }
    

    but this is only to know if such a property is defined in object itself, but not its parents. so if such property is inherited by the object, you can not test its existence like this.

    the other way is to test the property against undefined value. like this:

    if ( myObject.prop !== undefined ) {
        // prop exists
    }
    

    remember to use the !== operator instead of != because != will not differ between null and undefined, but !== does. so if your object has a property but the value is null, != will not help you. so this test:

    if ( myObject.prop ) {
    }
    

    might have wrong results if "prop" has a false or null value. but by comparing to undefined with !== operator, you can be sure that null/false values will not confuse you.

    0 讨论(0)
提交回复
热议问题