Benefit of using Object.hasOwnProperty vs. testing if a property is undefined

后端 未结 3 1948
心在旅途
心在旅途 2021-02-05 11:02

Since hasOwnProperty has some caveats and quirks (window / extensive use in Internet Explorer 8 issues, etc.):

Is there any reason to even use it

相关标签:
3条回答
  • 2021-02-05 11:18

    The hasOwnProperty method checks that a property is assigned to the object directly.

    So, if property 'a' is in the prototype, hasOwnProperty will filter that.

    function NewClass() {}
    NewClass.prototype = { a: 'there' };
    var obj = new NewClass();
    
    if (obj.hasOwnProperty('a')) { /* Code does not work */ }
    if (obj.a !== undefined) { /* Code works */ }
    

    So, hasOwnProperty is safer in many cases.

    0 讨论(0)
  • 2021-02-05 11:24

    hasOwnProperty does not check for undefined values. It only checks if a property is assigned to the object even if is undefined:

    var obj = { a : undefined };
    obj.hasOwnProperty("a") // true
    obj.a === undefined     // true
    obj.hasOwnProperty("b") // false
    obj.b === undefined     // true
    
    0 讨论(0)
  • 2021-02-05 11:26

    As further information to the answer given by Pavel Gruba, and the polyfil that you supplied:

    To the best of my knowledge, there is no good way to polyfil hasOwnProperty for browsers that do not support it natively. I have seen quite a few different ones in the wild and they all produce false positives or negatives. If I have absolutely no alternative then this is what I created for my use, but it also suffers false positives and negatives. According to MSDN.

    Supported in the following document modes: Quirks, Internet Explorer 6 standards, Internet Explorer 7 standards, Internet Explorer 8 standards, Internet Explorer 9 standards, Internet Explorer 10 standards. Also supported in Windows Store apps.

    JavaScript

    function is(x, y) {
        if (x === y) {
            if (x === 0) {
                return 1 / x === 1 / y;
            }
    
            return true;
        }
    
        var x1 = x,
            y1 = y;
    
        return x !== x1 && y !== y1;
    }
    
    function hasOwnProperty(object, property) {
        var prototype;
    
        return property in object && (!(property in (prototype = object.__proto__ || object.constructor.prototype)) || !is(object[property], prototype[property]));
    }
    
    function NewClass() {}
    NewClass.prototype = {
        a: 'there'
    };
    
    var obj = new NewClass();
    
    if (obj.hasOwnProperty("a")) {
        console.log("has property")
    }
    
    if (hasOwnProperty(obj, "a")) {
        console.log("has property")
    }
    

    On JSFiddle.

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