JavaScript中typeof抛出引用错误

3

让我们开始吧。
我正在使用typeof检查变量API是否存在。 我了解到如果该变量不存在,typeof会返回"undefined"。

function exitApplication() {
    let typeOfApi = typeof API;
    if (typeOfApi !== "undefined") {
        API.close(() => {
            strip.shutdown();
            ...
            ...
            ...
        });
    }
    else {
        console.log("Bye!");
        process.exit(0);
    }
}

如果我现在用测试数据运行我的程序,当API尚未定义时会调用exitApplication,那么我会得到一个ReferenceError错误。
    let typeOfApi = typeof API;
                    ^

ReferenceError: API is not defined

因为我在使用Webpack,所以我更改了输出文件,并用未定义的其他内容替换了API,然后就可以了,typeOfApi是"undefined"(我粘贴的代码是Webpack的输出)。
API是一个常量值,我在代码中只使用let和const。我读到了一些关于暂时性死区的东西,但是如果一个let变量没有被定义,typeof应该仍然返回"undefined"吗?
我还阅读了这篇文章Why does typeof only sometimes throw ReferenceError?但我没有使用表达式。
哦,我的代码是用typescript编写的。但是我不是那么“擅长”它,也不知道如何获取restify的类型,所以API的类型是any。(我知道typeof和typescript类型完全不同:D)。但是代码似乎仍然是1对1的翻译。
编辑:所以我做了这个小例子。这是Webpack的输出。
#!/usr/local/bin/node
/******/ (function(modules) { // webpackBootstrap
/******/    // The module cache
/******/    var installedModules = {};
/******/
/******/    // The require function
/******/    function __webpack_require__(moduleId) {
/******/
/******/        // Check if module is in cache
/******/        if(installedModules[moduleId]) {
/******/            return installedModules[moduleId].exports;
/******/        }
/******/        // Create a new module (and put it into the cache)
/******/        var module = installedModules[moduleId] = {
/******/            i: moduleId,
/******/            l: false,
/******/            exports: {}
/******/        };
/******/
/******/        // Execute the module function
/******/        modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/        // Flag the module as loaded
/******/        module.l = true;
/******/
/******/        // Return the exports of the module
/******/        return module.exports;
/******/    }
/******/
/******/
/******/    // expose the modules object (__webpack_modules__)
/******/    __webpack_require__.m = modules;
/******/
/******/    // expose the module cache
/******/    __webpack_require__.c = installedModules;
/******/
/******/    // define getter function for harmony exports
/******/    __webpack_require__.d = function(exports, name, getter) {
/******/        if(!__webpack_require__.o(exports, name)) {
/******/            Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/        }
/******/    };
/******/
/******/    // define __esModule on exports
/******/    __webpack_require__.r = function(exports) {
/******/        if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/            Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/        }
/******/        Object.defineProperty(exports, '__esModule', { value: true });
/******/    };
/******/
/******/    // create a fake namespace object
/******/    // mode & 1: value is a module id, require it
/******/    // mode & 2: merge all properties of value into the ns
/******/    // mode & 4: return value when already ns object
/******/    // mode & 8|1: behave like require
/******/    __webpack_require__.t = function(value, mode) {
/******/        if(mode & 1) value = __webpack_require__(value);
/******/        if(mode & 8) return value;
/******/        if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/        var ns = Object.create(null);
/******/        __webpack_require__.r(ns);
/******/        Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/        if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/        return ns;
/******/    };
/******/
/******/    // getDefaultExport function for compatibility with non-harmony modules
/******/    __webpack_require__.n = function(module) {
/******/        var getter = module && module.__esModule ?
/******/            function getDefault() { return module['default']; } :
/******/            function getModuleExports() { return module; };
/******/        __webpack_require__.d(getter, 'a', getter);
/******/        return getter;
/******/    };
/******/
/******/    // Object.prototype.hasOwnProperty.call
/******/    __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/    // __webpack_public_path__
/******/    __webpack_require__.p = "";
/******/
/******/
/******/    // Load entry module and return exports
/******/    return __webpack_require__(__webpack_require__.s = "./src/test.ts");
/******/ })
/************************************************************************/
/******/ ({

/***/ "./src/test.ts":
/*!*********************!*\
  !*** ./src/test.ts ***!
  \*********************/
/*! no static exports found */
/***/ (function(module, exports) {

exitApplication();
const API = {};
function exitApplication() {
    let typeOfApi = typeof API;
    console.log(typeOfApi);
    if (typeOfApi !== "undefined") {
        console.log("Bye!");
        process.exit(0);
    }
    else {
        console.log("Bye!");
        process.exit(0);
    }
}


/***/ })

/******/ });
//# sourceMappingURL=LED-Controller.js.map

这也将引发一个引用错误。

编辑:以下是我的TS和Webpack配置。 https://gist.github.com/Lucarus/ebbfab5cc6560094a292ba86557ffd1d
对于示例,我将Applications.ts替换为test.ts,但使用了相同的配置。


你尝试过只用 if(API){...} 吗? - Scott Marcus
你能展示一下你定义 API 的地方吗?还有,如果 API 是任意类型的,为什么要检查它的类型呢? - Sunil Lama
1
我不知道为什么会发生这种情况。我尝试重现了这个问题,但是没有成功。也许可以尝试删除一些代码片段,直到找到最小可重现的代码?但是我过去处理检查全局变量是否存在的方式是在函数中使用try/catch:const apiExists = () => { try { return !!API } catch(e) { return false } } - suddjian
1
@ScottMarcus请看一下我的问题。如果你传递给typeof一个未创建的变量,它将返回"undefined"。看看typeof文档 ;) - Lukas
1
这绝对是时间死区。 - Scott Marcus
显示剩余9条评论
1个回答

2

在声明 const API = {} 变量的作用域内,你调用了一个引用该变量的函数,但在变量初始化之前。使用 constlet 是不允许这样做的。你的代码如下:

exitApplication();
const API = {};
function exitApplication() {
    let typeOfApi = typeof API;
    console.log(typeOfApi);
    if (typeOfApi !== "undefined") {
        console.log("Bye!");
        process.exit(0);
    }
    else {
        console.log("Bye!");
        process.exit(0);
    }
}

该函数被提升到该作用域的顶部,这就是为什么您可以调用exitApplication(),但您尚未执行初始化API的代码行。 但是,解释器知道它在那里并且尚未初始化,并且在Javascript中,在包含其声明的行运行之前尝试访问在其定义所在的范围内定义的const或let变量是ReferenceError。
当我在Chrome中运行此代码时,我得到的确切错误是:
Uncaught ReferenceError: Cannot access 'API' before initialization

这段文字涉及到IT技术,它告诉你出现的问题是什么。在解释器的第一次解析中,它已经解析了代码并知道const API = {}的存在,因此在初始化该行代码之前访问它是非法的。如果你真的想绕过这个问题,可以将const更改为var,但很可能有更好的编写代码的方法,不需要使用var


当然,如果你只是将API的声明向上移动一行,就没有问题了:

const API = {};
exitApplication();
function exitApplication() {
    let typeOfApi = typeof API;
    console.log(typeOfApi);
    if (typeOfApi !== "undefined") {
        console.log("Bye!");
        process.exit(0);
    }
    else {
        console.log("Bye!");
        process.exit(0);
    }
}

关于这个主题的好文章,你可以阅读:为什么typeof不再安全


是的,我明白了,但是typeof不应该捕获吗?我知道我必须“欺骗”TypeScript检查器才能将其编译为js。 但问题是,如果我在解释模式下打开节点,可以键入代码并逐行解释(就像在终端中运行节点命令一样^^)。我可以键入“typeof foo”,它将返回“undefined”。而且,如果我在我的代码中将变量API更改为任何其他内容,例如foobar,它也会起作用。 var的原因是它创建了每个使用var声明的变量,即使解释器尚未到达其声明。 - Lukas
好的,我现在明白了,你的意思是因为解释器知道会有一个API变量,所以它会抛出引用错误? 如果我想引用一个不存在的变量,而解释器不知道它的存在,它会返回“未定义”? 这是否与时间死区有关,以及如何处理let和var的不同之处? 如何检查API的存在,我可以使用try catch,或者重新设计我的代码,使其在定义API之前不被调用。谢谢;) - Lukas
你能在你的回答中加入http://es-discourse.com/t/why-typeof-is-no-longer-safe/15吗?这让我更清楚了^^ - Lukas
@Lukas - 已添加到我的答案中。 - jfriend00

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接