javascript 使用 Object.hasOwnProperty 与测试 Property 是否未定义的好处

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17150396/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 07:16:31  来源:igfitidea点击:

Benefit of using Object.hasOwnProperty vs testing if Property is undefined

javascriptjqueryobjectundefinedhasownproperty

提问by Mark Pieszak - Trilon.io

Since hasOwnPropertyhas some caveats and quirks (window / extensive use in ie8 issues / etc).

由于hasOwnProperty有一些警告和怪癖(窗口/在 ie8 问题中的广泛使用/等)。

I was wondering if there is any reason to even use it, and if simply testing if a property is undefined is better justified & more simplistic.

我想知道是否有任何理由甚至使用它,如果简单地测试属性是否未定义更合理且更简单。

For example:

例如:

var obj = { a : 'here' };

if (obj.hasOwnProperty('a')) { /* do something */ }

if (obj.a !== undefined) { /* do something */ }
// or maybe (typeof (obj.a) !== 'undefined')

Just wondering if anyone has any good insight on this, I'd prefer to be using the most cross-browser friendly, and up to date methodology.

只是想知道是否有人对此有任何很好的见解,我更愿意使用最跨浏览器友好和最新的方法。

I've also seen this prototype over-write for hasOwnProperty, which works, but I'm not sold on it's usefulness...

我还看到这个原型覆盖了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]);
    };
}

采纳答案by Xotic750

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 hasOwnPropertyfor 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, it also suffers false positives and negatives. According to MSDN.

作为@Pavel Gruba 给出的答案的进一步信息,以及您提供的 polyfil。据我所知,对于原生hasOwnProperty不支持它的浏览器,没有好的方法来 polyfil 。我在野外见过很多不同的,它们都会产生假阳性或阴性。如果我绝对别无选择,那么这就是我为我的用途而创建的,它也会遭受误报和否定。根据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.

支持以下文档模式:Quirks、Internet Explorer 6 标准、Internet Explorer 7 标准、Internet Explorer 8 标准、Internet Explorer 9 标准、Internet Explorer 10 标准。Windows 应用商店应用也支持。

Javascript

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

jsfiddle 上

回答by Pavel Gruba

The hasOwnProperty method checks that property is assigned to object directly. So, if property 'a' is in prototype hasOwnProperty will filter that.

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 */ }

So, hasOwnProperty is safer in many cases.

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

回答by dpineda

hasOwnProperty does not check for undefined values only checks if property is asigned to the object even if is undefined

hasOwnProperty 不检查未定义的值仅检查属性是否分配给对象,即使未定义

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