【问题标题】:Node.js module.exports multiple classesNode.js module.exports 多个类
【发布时间】:2015-05-18 18:19:14
【问题描述】:

我有 2 个名为 a.js 和 b.js 的文件,它们都包含类。我正在尝试使用以下代码在 A 类中导入并创建 B 类的新实例

a.js

module.exports.A = A;
var classB = require('./b.js').B;
A.protoype.Init = function(){
this.B = new classB();

b.js

module.exports.B = B;
function B(a_class)
{
  this.a = a_class;
}

我收到以下错误

TypeError: undefined is not a function at this.B = new class B();

【问题讨论】:

  • 在 b.js 中,B 是否定义为函数?如果这是你的整个 b.js 文件,那么 BundefinedclassB 在 a.js 文件中也是如此。
  • 问题在于您对B 的定义,因此您需要显示b.js 的那部分。
  • 看起来应该可以正常工作,除非b.js 中有其他代码以某种方式修改了B 的值。
  • 您的括号在a.js 中不匹配,这让我认为导致它无法按预期工作的代码丢失了。尝试提出一个展示问题的最小示例,并将其添加到您的问题中。

标签: javascript node.js


【解决方案1】:

你还没有在你的 a.js 文件中定义你的 A 类:

a.js - 我为你的 A 类添加了一个构造函数:

module.exports.A = A;
var classB = require('./b.js').B;

function A() {}

A.protoype.Init = function(){
    this.B = new classB();
}

【讨论】:

    猜你喜欢
    • 2013-05-13
    • 2012-08-31
    • 1970-01-01
    • 2019-01-02
    • 1970-01-01
    • 2011-10-31
    • 2015-08-19
    • 2016-12-09
    相关资源
    最近更新 更多