javascript - 如何使用 module.export 将 javascript 中的特定变量导出到节点
问题描述
我有一个名为的函数startTime()
,其中包含一个设置为时间函数小时的变量 h。我将 h 与全局化globalThis
并希望将其导出到我的节点端,但在导出后 h 变得未定义。为了调试 h 是否实际设置为一个值,我创建了一个名为的新函数exportVariable()
,其中包含一个alert(h)
. 当我exportVariable()
从客户端/html 端运行时,它会正确提醒函数的当前小时,startTime()
因此这意味着 h 已定义。什么可能导致 h 在导出后未定义?我当前的 javascript 和节点端代码附在下面。错误位置在 javascript 端。
JavaScript
function startTime() {
var today = new Date();
globalThis.h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('txt').innerHTML =
h + ":" + m + ":" + s;
var t = setTimeout(startTime, 500);
}
function checkTime(i) {
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
var currentTime = h;
function exportVariable(){
alert(h)
}
module.exports = {
currentTime,
};
节点
const isModule = require('./index.js');
const time = isModule.currentTime;
错误
var currentTime = h;
^
ReferenceError: h is not defined
at Object.<anonymous>
解决方案
我看到的主要问题是函数从未被调用。h
是在里面定义的startTime()
,但是这个函数在赋值之前没有被调用var currentTime = h
,所以h
实际上是undefined
存在的。
它应该是:
function startTime() {
var today = new Date();
globalThis.h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('txt').innerHTML =
h + ":" + m + ":" + s;
var t = setTimeout(startTime, 500);
}
function checkTime(i) {
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
startTime() //ADDED ON SOLUTION
var currentTime = h;
function exportVariable(){
alert(h)
}
module.exports = {
currentTime,
};
推荐阅读
- c - Speck 128/256 实现错误的测试向量
- asp.net-core - 从 OnValidatePrincipal 重定向到 IDP/登录
- grafana - Grafana OAuth:自签名证书
- python - Selenium + Python 等待元素包含随机生成的数字字符串
- three.js - ExtrudeBufferGeometry 导致输出旋转
- r - 如果语句为真,则修改几列
- python - 尝试使用python从复杂的嵌套XML字段中的值中提取列表
- python - OpenCV videocapture 在调用 isOpened() 时返回 False,但另一个代码示例运行良好
- reactjs - 如何使用材料 ui 构建表单以正确反应
- python - 如果我们在 apscheduler 中安排许多作业会发生什么