JavaScript 对象检测:点语法与“in"关键字 [英] JavaScript object detection: dot syntax versus 'in' keyword

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

问题描述

我见过两种检测 UA 是否实现特定 JS 属性的方法:if(object.property)if('property' in object).

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.

鼓励读者在 jsperf.com/object 上运行测试-检测

推荐答案

  • if(object.property)

    将在未设置的情况下失败(这是您想要的), 在它已设置为某个假值的情况下,例如undefinednull0 等等(这不是你想要的).

    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('property' in object)

    稍微好一点,因为它实际上会返回对象是否真的具有该属性,而不仅仅是通过查看它的值.

    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
    

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

    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"关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆