【问题标题】:Global Context - Check for undefined全局上下文 - 检查未定义
【发布时间】:2015-03-23 12:00:15
【问题描述】:

为什么下面的代码会导致三次true

第二步我排除了false

    function foo() {
        this.bar = function () { };
    };

    console.log("foo - defined : " + typeof window.foo !== 'undefined');
    console.log("bar - defined : " + typeof window.bar !== 'undefined');

    foo();

    console.log("bar - defined : " + typeof window.bar !== 'undefined');

【问题讨论】:

  • 你应该是:(typeof window.foo !== 'undefined')

标签: javascript function typeof


【解决方案1】:

+ 运算符的优先级高于!==。你的表情意味着

("bar - defined : " + typeof window.bar) !== 'undefined' // always true (or an exception)

而不是

"bar - defined : " + (typeof window.bar !== 'undefined')

如果你明确地做后者,你会得到预期的输出:

foo - defined : true
bar - defined : false
bar - defined : true

【讨论】:

    猜你喜欢
    • 2010-09-27
    • 2014-07-26
    • 2022-10-19
    • 2017-03-23
    • 2012-08-17
    • 2020-06-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多