Detecting an undefined object property

后端 未结 30 2852
花落未央
花落未央 2020-11-21 04:43

What\'s the best way of checking if an object property in JavaScript is undefined?

30条回答
  •  灰色年华
    2020-11-21 05:27

    'if (window.x) { }' is error safe

    Most likely you want if (window.x). This check is safe even if x hasn't been declared (var x;) - browser doesn't throw an error.

    Example: I want to know if my browser supports History API

    if (window.history) {
        history.call_some_function();
    }
    

    How this works:

    window is an object which holds all global variables as its members, and it is legal to try to access a non-existing member. If x hasn't been declared or hasn't been set then window.x returns undefined. undefined leads to false when if() evaluates it.

提交回复
热议问题