javascript - CommonJS 模块在调用时返回未定义

标签 javascript node.js module undefined commonjs

我对模块化 JS 完全陌生,以前从未使用过任何模式。我正在编写一个项目,其中的代码多达 400 多行,我想通过将不同模块中的内容分开来更好地管理它。我选择使用 commonJS 模块,因为我已经使用了 webpack。现在,我将第一个函数放在不同的模块中,然后将其导出,如下所示:

//init.js file
var initt = function () {
  octaveNumber = document.getElementById("octaveNum");
  audioCtx = new (window.AudioContext || window.webkitAudioContext);
  osc = audioCtx.createOscillator();
  volume = audioCtx.createGain();
  filter = audioCtx.createBiquadFilter();
  osc.connect(filter);
  volume.connect(audioCtx.destination);
  booleanVal = false;
  osc.frequency.value = dial.value
  osc.start();
  gainDisplay.innerHTML = gainSlider.value;
  noteSetOscFreq()
  octaveUpClick()
  octaveDownClick()
  waveFormSelector()
}

module.exports = initt;

在我的主 JS 文件中我需要它

var messages = require('./init');

最后在 If 语句中调用该函数:

if (!localStorage.getItem("presetsArr") {
  messages.initt;

不幸的是,我在控制台中收到Cannot read property 'gain' of undefined,这意味着 Init 模块没有按照预期初始化变量和其他内容。当我在不使用 commonJS 模块的情况下将整个函数放回去时,它工作得很好。我知道这可能与返回值有关,但我无法动手。什么都不起作用。

最佳答案

messages.init() X

消息() √

关于javascript - CommonJS 模块在调用时返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46702309/

相关文章:

javascript - 从另一个 iframe 中的链接在 iframe 中加载页面

javascript - 如何分离日期输入 Bootstrap 日期范围选择器

javascript - 语法错误 : Unexpected token *

node.js - PRISMA:身份验证 token 无效:未提供 'Authorization' header

node.js - 当nestjs中的正文验证失败时如何阻止文件上传

node.js - 如何将 NPM 模块(十进制)添加到 ArangoDB 以进行 ACID 事务

javascript - 使用 display none 而不是 html 呈现 html

javascript - vue-router beforeRouteUpdate 钩子(Hook)无法访问 `this`

module - 重用maven模块作为依赖项

mysql - 什么是 TYPO3 引用索引?为什么它会包含过时的值?