多个文件中的javascript构造函数存在问题
我正在尝试用javascript制作和测试一个trie,并将节点、trie和test拆分为单独的文件。我使用node.js在文件之间共享代码。我曾尝试过处理导出和require,但一直得到一个类型错误,表示导入不是构造函数 在trinode.js中多个文件中的javascript构造函数存在问题,javascript,node.js,Javascript,Node.js,我正在尝试用javascript制作和测试一个trie,并将节点、trie和test拆分为单独的文件。我使用node.js在文件之间共享代码。我曾尝试过处理导出和require,但一直得到一个类型错误,表示导入不是构造函数 在trinode.js中 function trieNode(val, par) { this.value = val; this.children = {}; this.isWord = false; this.freq = 0; this.parent
function trieNode(val, par) {
this.value = val;
this.children = {};
this.isWord = false;
this.freq = 0;
this.parent = par;
}
trieNode.prototype.getValue = function() {
return this.value;
}
module.exports.tn = trieNode();
在trie.js中
var trieNode = require('./trienode.js').tn;
function Trie() {
console.log('initialize trie');
console.log(typeof trieNode);
this.root = new trieNode(null);
this.saved = {}
this.current;
}
Trie.prototype.insert = function(word) {
}
Trie.prototype.findSuggestions = function(prefix) {
}
module.exports = Trie();
在test.js中
var Trie = require('./trie.js');
var trieNode = require('./trienode.js').tn;
var tr = new Trie();
tr.insert("boot");
tr.insert("boot");
tr.insert("boot");
tr.insert("book");
tr.insert("book");
tr.insert("boom");
var sug = tr.findSuggestions("boo");
for(s in sug) {
console.log(s);
}
这就是我得到的错误
TypeError: trieNode is not a constructor
at Trie (C:\Users\agnu\Desktop\autocomplete\trie.js:6:15)
at Object.<anonymous> (C:\Users\agnu\Desktop\autocomplete\trie.js:94:18)
at Module._compile (module.js:653:30)
at Object.Module._extensions..js (module.js:664:10)
at Module.load (module.js:566:32)
at tryModuleLoad (module.js:506:12)
at Function.Module._load (module.js:498:3)
at Module.require (module.js:597:17)
at require (internal/module.js:11:18)
at Object.<anonymous> (C:\Users\agnu\Desktop\autocomplete\test.js:1:74)
TypeError:三节点不是构造函数
在Trie(C:\Users\agnu\Desktop\autocomplete\Trie.js:6:15)
反对。(C:\Users\agnu\Desktop\autocomplete\trie.js:94:18)
编译(Module.js:653:30)
在Object.Module.\u extensions..js(Module.js:664:10)
在Module.load(Module.js:566:32)
在tryModuleLoad时(module.js:506:12)
在Function.Module.\u加载(Module.js:498:3)
at Module.require(Module.js:597:17)
根据需要(内部/module.js:11:18)
反对。(C:\Users\agnu\Desktop\autocomplete\test.js:1:74)
导出的是函数的结果,而不是函数本身
如果要在导入函数后调用该函数,只需导出函数:
module.exports.tn = trieNode;
及
然后,在导入它们之后,调用函数。导出的是函数的结果,而不是函数本身 如果要在导入函数后调用该函数,只需导出函数:
module.exports.tn = trieNode;
及
然后,在导入它们之后,调用函数。我没有发现这个问题,但是谢谢你的帖子。当构造函数需要两个参数时,传递一个参数是否有效?@RyanWilson您不必将所有参数传递给函数。如果不这样做,函数中的值将为undefined。@MarkMeyer啊,谢谢你的澄清。我习惯于在C#中使用编译器错误,如果您试图调用参数少于所定义参数的构造函数。我将删除我的评论+我没有发现这个问题,但是谢谢你的帖子。当构造函数需要两个参数时,传递一个参数是否有效?@RyanWilson您不必将所有参数传递给函数。如果不这样做,函数中的值将为undefined。@MarkMeyer啊,谢谢你的澄清。我习惯于在C#中使用编译器错误,如果您试图调用参数少于所定义参数的构造函数。我将删除我的评论+从我这里得到1。