JavaScript对象检测

JavaScript对象检测

本文介绍了JavaScript对象检测:点语法与'in'关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到两种检测UA是否实现特定JS属性的方法: if(object.property) if('property'在对象中)

I have seen two ways of detecting whether a UA implements a specific JS property: if(object.property) and if('property' in object).

我想听听关于哪个更好,最重要的是,为什么的意见。一个明显优于另一个吗?是否有不仅仅是这两种方法来进行对象属性检测?请涵盖浏览器支持,陷阱,执行速度等,而不是美学。

I would like to hear opinions on which is better, and most importantly, why. Is one unequivocally better than the other? Are there more than just these two ways to do object property detection? Please cover browser support, pitfalls, execution speed, and such like, rather than aesthetics.

编辑:鼓励读者在以下位置运行测试

Readers are encouraged to run the tests at jsperf.com/object-detection

推荐答案


  • if(object.property)

    将失败,如果未设置(这是你想要的),,如果它已被设置为某些假值,例如 undefined null 0 etc(这不是什么你想要的。)

    will fail in cases it is not set (which is what you want), and in cases it has been set to some falsey value, e.g. undefined, null, 0 etc (which is not what you want).

    var object = {property: 0};
    if(object.isNotSet) { ... } // will not run
    if(object.property) { ... } // will not run
    


  • if('对象中的'属性')

    略好一些,因为它实际上会返回对象真的是否具有该属性,而不仅仅是通过查看其值。

    is slightly better, since it will actually return whether the object really has the property, not just by looking at its value.

    var object = {property: 0};
    if('property' in object) { ... } // will run
    if('toString' in object) { ... } // will also run; from prototype
    


  • if(object.hasOwnProperty('property') )

    甚至更好,因为它可以让你区分实例属性和原型属性。

    is even better, since it will allow you to distinguish between instance properties and prototype properties.

    var object = {property: 0};
    if(object.hasOwnProperty('property')) { ... } // will run
    if(object.hasOwnProperty('toString')) { ... } // will not run
    


  • 我会说性能不是那么大问题在这里,除非你每秒检查数千次,但在这种情况下你应该考虑另一种代码结构。所有这些功能/语法都受到最近浏览器的支持,也已存在很长时间了。

    I would say performance is not that big of an issue here, unless you're checking thousands of time a second but in that case you should consider another code structure. All of these functions/syntaxes are supported by recent browsers, hasOwnProperty has been around for a long time, too.

    编辑:您还可以通过将任何东西(甚至是非对象的东西)作为对象传递来检查是否存在属性:

    You can also make a general function to check for existence of a property by passing anything (even things that are not objects) as an object like this:

    function has(obj, prop) {
        return Object.prototype.hasOwnProperty.call(obj, prop);
    }
    

    现在可行:

    has(window, 'setTimeout'); // true
    

    即使 window.hasOwnProperty === undefined (在IE 8或更低版本中就是这种情况)。

    even if window.hasOwnProperty === undefined (which is the case in IE version 8 or lower).

    这篇关于JavaScript对象检测:点语法与'in'关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 11:49