gpt4 book ai didi

Javascript typeof 抛出引用错误

转载 作者:行者123 更新时间:2023-12-03 19:02:33 25 4
gpt4 key购买 nike

让我们开始吧。
我正在使用 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 是“未定义的”(我粘贴的代码是 Webpack outup) .

API 是一个常量值,我只在我的代码中使用 let 和 const。我阅读了一些关于时间死区的内容,但如果未定义 let 变量,typeof 仍应返回“undefined”?

我也读过这个Why does typeof only sometimes throw ReferenceError?但我没有使用表达式。

哦,我的代码是用 typescript 写的。但我不是那么“擅长”,也不知道如何获取 restify 的类型,所以 APIany 类型。 (我知道 typeof 和 typescript 类型是完全不同的东西 :D)。但无论如何,代码似乎都是一对一翻译的。


编辑:所以我做了这个小例子。这是 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,但它使用相同的配置。

最佳答案

您正在调用一个引用 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 中的 ReferenceError 试图访问 constlet 中定义的变量在包含其声明的行之前定义它的范围。

当我在 Chrome 中运行它时,我得到的确切错误是:

Uncaught ReferenceError: Cannot access 'API' before initialization

它准确地告诉您问题出在哪里。在解释器的第一遍中,它已经解析了代码并且知道 const API = {} 在那里,因此在到达初始化它的那行代码之前访问它是非法的。如果你真的想解决这个问题,那么将 const 更改为 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);
}
}

有关此主题的好文章,您可以阅读这篇文章:Why typeof is no longer safe .

关于Javascript typeof 抛出引用错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60311164/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com