【问题标题】:How can I avoid the error when an undefined variable is referred to in JavaScript [duplicate]在 JavaScript [重复] 中引用未定义变量时如何避免错误
【发布时间】:2015-05-23 00:18:52
【问题描述】:

以下在浏览器中抛出错误“模块未定义”。鉴于我无法提前确定该模块将被定义,为什么以及如何避免该错误?

;(function() {
    var version = '0.0.1';

    /**
     * This file needs to work in
     * both NodeJS and browsers.
     */
    if (module) {
        module.exports = version;
    } else {
        define(function() {
            return version;
        });
    }
}());

【问题讨论】:

标签: javascript


【解决方案1】:

添加此检查以查看是否已定义 module

if(typeof module !== "undefined") {
    // do stuff
}

在您的示例中,您得到一个异常,因为 module 在达到您的条件时尚未声明或分配。因此,当您尝试通过执行if(module) 检查它是否为空时,该变量从未被分配,因此它会抛出异常。如果在您执行var module = null 的条件之前,您的代码将起作用。即使您将其设置为null,它已被分配,所以它不是undefined

使用typeof 允许标识符以前从未被声明过,因此您可以避免遇到的异常。

【讨论】:

  • 为什么这行得通,而我的例子却不行?
  • @BenAston 我编辑了我的答案,试图解释其中的区别。
  • 但我没有检查空值。我正在检查真实性。 moduleundefined,因此应该强制转换为 false。我不是在严格模式下,所以不应该抛出错误,不是吗?
  • var foo; if (foo) {... is different of if (foo) {... in the last case you will get the error because there is no foo var, or, in your case, the module var
猜你喜欢
  • 1970-01-01
  • 2020-01-21
  • 2010-11-14
  • 2018-12-02
  • 1970-01-01
  • 2019-11-28
  • 1970-01-01
  • 1970-01-01
  • 2016-12-26
相关资源
最近更新 更多