与 object.prop 相比,使用 `in` 有什么好处?

2024-03-12

我们都看到该功能检测到执行以下操作:

var touch = function () {
  return 'ontouchstart' in window;
};

但我想知道使用它是否还有其他好处in类似这样的操作符(这可以节省一些字节)?

var touch = function () {
  return !!window.ontouchstart;
};

使用还有其他好处吗in?


他们两者完全不同。

当你这样做时

!!window.ontouchstart

您正在检查的值是否为window.ontouchstart is truthy http://docs.nodejitsu.com/articles/javascript-conventions/what-are-truthy-and-falsy-values, but

'ontouchstart' in window

检查是否ontouchstart存在于window目的。

另一个问题与使用!!window.ontouchstart检查成员是否存在是这样的,即使ontouchstart存在并且如果它有一个假值,例如undefined, null, false or 0,它仍然会返回false。因此,它不应该用于检查成员是否存在。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

与 object.prop 相比,使用 `in` 有什么好处? 的相关文章

随机推荐