【问题标题】:CommonJS module returning undefined when is calledCommonJS 模块在被调用时返回未定义
【发布时间】:2017-10-12 05:51:57
【问题描述】:

我对模块化 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 模块的情况下放回整个函数时,它工作得很好。我知道这可能与返回值有关,但我不能动手。什么都没有。

【问题讨论】:

    标签: javascript node.js module undefined commonjs


    【解决方案1】:

    messages.initt() X

    消息() √

    【讨论】:

    • 现在我没有得到未定义的问题,谢谢。这是题外话,但我收到另一个错误Uncaught TypeError: Failed to set the 'value' property on 'AudioParam': The provided float value is non-finite. 它可以解决 commonjs 的同步问题吗?因为就像我说的,如果我不使用模块,一切都会正常工作。
    • 因为没有完整的代码,我不能保证我的答案。我想你可以看看一些commonjs规范文档,可能有范围问题。如你所见,我不擅长英语,希望你能明白我所说的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-01
    • 1970-01-01
    • 2016-11-18
    • 2018-02-20
    相关资源
    最近更新 更多