簡體   English   中英

使用 Object.hasOwnProperty 與測試屬性是否未定義的好處

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

由於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 方法檢查屬性是否直接分配給對象。

因此,如果屬性 '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 在許多情況下更安全。

hasOwnProperty 不檢查未定義的值。 它只檢查屬性是否分配給對象,即使未定義:

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

作為Pavel Gruba 給出的答案的進一步信息,以及您提供的 polyfil:

據我所知,對於原生不支持它的瀏覽器,沒有很好的方法來 polyfil hasOwnProperty 我在野外見過很多不同的,它們都會產生假陽性或陰性。 如果我絕對別無選擇,那么這就是我為我的用途而創建的,但它也會遭受誤報和誤報。 根據MSDN

支持以下文檔模式:Quirks、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 上

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM