使用 Object.hasOwnProperty 与测试属性(如果属性未定义)的好处

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

本文关键字:属性 未定义 如果 Object hasOwnProperty 测试 使用      更新时间:2023-09-26

由于hasOwnProperty有一些警告和怪癖(窗口/在Internet Explorer 8问题中广泛使用等(:

甚至有什么理由使用它吗?如果简单地测试一个属性是否未定义,它是否更合理且更简单?

例如:

var obj = { a : 'here' };
if (obj.hasOwnProperty('a')) { /* do something */ }
if (obj.a !== undefined) { /* do something */ }
// Or maybe (typeof (obj.a) !== 'undefined')

我更喜欢使用跨浏览器友好和最新的方法。

我也看到这个原型被覆盖为 hasOwnProperty,它可以工作,但我不相信它的有用性......

if (!Object.prototype.hasOwnProperty) {
    Object.prototype.hasOwnProperty = function(prop) {
        var proto = this.__proto__ || this.constructor.prototype;
        return (prop in this) && (!(prop in proto) || proto[prop] !== this[prop]);
    };
}

hasOwnProperty 不检查未定义的值。它只检查是否将属性分配给对象,即使未定义:

var obj = { a : undefined };
obj.hasOwnProperty("a") // true
obj.a === undefined     // true
obj.hasOwnProperty("b") // false
obj.b === undefined     // true

方法检查属性是否直接分配给对象。

因此,如果属性"a"在原型中,hasOwnProperty 将过滤它。

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

因此,在许多情况下,hasOwnProperty更安全。

作为Pavel Gruba给出的答案以及您提供的polyfil的进一步信息:

据我所知,对于本机不支持它的浏览器,没有好的方法可以 polyfil hasOwnProperty。我在野外见过很多不同的,它们都会产生假阳性或假阴性。如果我绝对别无选择,那么这就是我为我使用而创建的,但它也遭受误报和误报。根据MSDN。

在以下文档模式下受支持:怪癖、Internet Explorer 6标准, Internet Explorer 7 标准, Internet Explorer 8标准, Internet Explorer 9 标准, Internet Explorer 10标准。在 Windows 应用商店应用中也受支持。

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")
}

在JSFiddle上。