javascript - '类型错误 : undefined is not a function' when jumping 'tween modules

标签 javascript node.js typeerror

我在 Node 中不断遇到这个问题,每当我相互调用函数时,我的应用程序就会崩溃。

我已经做了这个最小的工作示例(按照它的方式工作给了我错误):

启动模块

var module2 = require('./module2');

var data = 'data';

module2.doStuff(data);

模块 2

var module3 = require('./module3');

function doStuff(data){
    // Stuff happens to 'data'
    module3.takeStuff(data);
}

function doSomethingElse(data){
    console.log(data);
}


module.exports = {
    doStuff: doStuff,
    doSomethingElse: doSomethingElse
};

模块 3

var module2 = require('./module2');

function takeStuff(data){
    // Stuff happens to 'data'
    module2.doSomethingElse(data); // I get the type error here
}

module.exports = {
    takeStuff: takeStuff
};

我得到的错误是:

module2.doSomethingElse(data); // I get the type error here
        ^
TypeError: undefined is not a function

start modulemodule2 中调用函数最终调用 module3 中的函数,它又调用了 module2 中的一个函数.

正确需要所有模块,它在 module2 中找到第一个方法就好了。

这里发生了什么?当需要从附带的模块中获取功能时,如何处理此模式?

编辑

调试显示该模块存在,但除了它的原型(prototype)之外它是空的。我的问题是为什么?在 Node/JavaScript 内部,这里发生了什么?

最佳答案

这里的这个问题可以很容易地解决,同时保持你的应用程序的结构(这很好,关于循环引用)。

您只需要保留系统为您的模块提供的默认exports 对象。不要用 module.exports = {...} 改变它。

以下应该有效:

启动模块

var module2 = require('./module2');

var data = 'data';

module2.doStuff(data);

模块 2

var module3 = require('./module3');

exports.doStuff = function doStuff(data){
    // Stuff happens to 'data'
    module3.takeStuff(data);
};

exports.doSomethingElse = function doSomethingElse(data){
    console.log(data);
};

模块 3

var module2 = require('./module2');

exports.takeStuff = function takeStuff(data){
    // Stuff happens to 'data'
    module2.doSomethingElse(data); // I get the type error here
};

解释

我将尝试从您的起点的第一行开始解释发生了什么:

  1. 在 start.js 中,您需要 module2 并且它尚未加载:执行 module2.js 中的代码
  2. 在 module2.js 中,您需要 module3 并且它尚未加载:来自 module3.js 的代码已执行
  3. 在 module3.js 中,您需要 module2,它已经加载:module2 变量现在包含来自 module2 的导出对象。
  4. module3 的其余部分已执行,您可以使用 module.exports = {...} 更改其导出对象
  5. 在 module2.js 中,module3 变量现在包含来自 module3 的导出对象。
  6. 执行 module2.js 的其余部分,并使用 module.exports = {...} 更改其导出对象
  7. 在 start.js 中,module2 变量现在包含来自 module2 的导出对象。

这里的问题在第 3 点和第 6 点之间。在您更改对它的引用 (6) 之前,模块 3 正在接收模块 2 (3) 的导出。 使用 exports.method = ... 解决了这个问题,因为 exports 对象永远不会改变。

关于javascript - '类型错误 : undefined is not a function' when jumping 'tween modules,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31783473/

相关文章:

Python 类型错误 : 'NoneType' object is not iterable

python - 类型错误:启动 Spyder 5.2.2 时出现预期字符串或类似字节的对象

node.js - Nodejs中使用Kurento实现群组调用

python - 代码给出了 TypeError

javascript - 为什么闭包比 JavaScript 中的全局变量更安全?

javascript - 关于Jscolor如何申请不同的ID

javascript - twbs分页不显示数据

javascript - JSON/javascript成员函数在dojo模块中引用父级?

javascript - 如何让 Express 路由默认需要身份验证?

javascript - 为多个测试文件运行 Mocha 时防止测试污染所需模块