Javascript Node.js引用错误:未定义类名
我有一个文件bloom.js,如下所示:Javascript Node.js引用错误:未定义类名,javascript,node.js,Javascript,Node.js,我有一个文件bloom.js,如下所示: function Bloom(k, m, n, hashFunction){ if(!m) m = 1000 this.m = m; if(!n) n = 100 this.n = n; if(!k) k = Math.max(Math.round(m / n * Math.LN2),
function Bloom(k, m, n, hashFunction){
if(!m)
m = 1000
this.m = m;
if(!n)
n = 100
this.n = n;
if(!k)
k = Math.max(Math.round(m / n * Math.LN2), 1)
this.k = k
this.insert = function(string){
for(var i = 0; i < this.k; i++){
var index = parseInt(this.hashFunction(i + string), 16) % this.array.length
this.array[index] = 1;
}
return true;
}
}
module.exports = Bloom;
函数Bloom(k,m,n,hashFunction){
如果(!m)
m=1000
这个,m=m;
如果(!n)
n=100
这个,n=n;
如果(!k)
k=数学最大值(数学四舍五入(m/n*Math.LN2),1)
这个。k=k
this.insert=函数(字符串){
对于(var i=0;iTypeError: Bloom is not a function
at Object.<anonymous> (J:\code\Main.js:114:13)
at Module._compile (module.js:409:26)
TypeError:Bloom不是函数
反对。(J:\code\Main.js:114:13)
在模块处编译(Module.js:409:26)
如何解决此错误?我也尝试了导出模块,但没有成功 是否从该文件导出函数Bloom?在
main.js
模块中没有Bloom
变量require
不是将所有源粘贴到代码中的#include
,它只返回对模块导出值的引用。在文件上使用require
不会自动将该文件中的所有项移动到当前上下文中Bloom
需要导出,您仍然需要导入它(以某种形式使用require
。@JaredSmith请检查Editedquestion@DivyanshuPathania:Bloom函数的内容无关紧要。显示带有模块的代码。导出
。如果导入的名称是bf
,则它可能应该是new bf
或new bf.Bloom
,而不是new Bloom
。您编辑的问题看起来仍然没有遵循建议。查看我对代码的扩展建议。现在我得到了TypeError:Bloom不是函数也不是函数。main.js和Bloom.js在同一个文件夹中吗?它们在同一个文件夹中。我可以将上述内容复制并粘贴到main.js和Bloom.js中,它们工作正常。关于你的设置有些东西你没有告诉我们。从命令行运行node--version时会得到什么?
// bloom.js
function Bloom(k, m, n, hashFunction){
if(!m)
m = 1000
this.m = m;
if(!n)
n = 100
this.n = n;
if(!k)
k = Math.max(Math.round(m / n * Math.LN2), 1)
this.k = k
this.insert = function(string){
for(var i = 0; i < this.k; i++){
var index = parseInt(this.hashFunction(i + string), 16) % this.array.length
this.array[index] = 1;
}
return true;
}
}
module.exports = Bloom;
// NOTE! the variable name here is what matters, not what you defined in bloom.js
var Bloom = require("./bloom");
var bloom = new Bloom();