What benefit does using `in` have over object.prop?

前端 未结 1 854
Happy的楠姐
Happy的楠姐 2021-01-28 18:13

We all see the feature detects doing something like:

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

But I\'m wondering if th

1条回答
  •  情话喂你
    2021-01-28 18:24

    They both are entirely different.

    When you do

    !!window.ontouchstart
    

    you are checking if the value of window.ontouchstart is truthy, but

    'ontouchstart' in window
    

    checks if ontouchstart exists in window object.

    Another problem with using !!window.ontouchstart to check member existence is that, even if ontouchstart exists and if it has a falsy value, for example undefined, null, false or 0, it will still return false. So, it should NOT be used to check the member existence.

    0 讨论(0)
提交回复
热议问题