2016-05-11 35 views
-1

我有一個文件bloom.js是如下:Node.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; 

在我main.js這樣做時,我得到錯誤:

var Bloom = require(「./ bloom」); var bloom = new Bloom();

錯誤:

TypeError: Bloom is not a function 
at Object.<anonymous> (J:\code\Main.js:114:13) 
at Module._compile (module.js:409:26) 

我怎樣才能解決這個問題?我也試過出口模塊,但它沒有奏效。

+2

你從該文件導出功能開花嗎? –

+1

「main.js」模塊中沒有'Bloom'變量。 'require'不是將所有源代碼粘貼到代碼中的'#include',它只是返回對模塊導出值的引用。 – Bergi

+1

在文件中使用'require'不會自動將該文件中的所有項目移動到當前上下文中。 「Bloom」需要導出,並且您仍然需要導入它(使用'require'以某種形式或另一種形式)。 – dvlsg

回答

2
// 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; 

然後,在main.js:

// NOTE! the variable name here is what matters, not what you defined in bloom.js 
var Bloom = require("./bloom"); 
var bloom = new Bloom(); 
+0

這不工作,請參閱更新的問題。 –

+0

您編輯的問題看起來仍然不符合您的建議。請參閱我對代碼的擴展建議。 – Paul

+0

現在我越來越TypeError:布盧姆不是一個函數不是一個函數。 –