2015-09-21 102 views
1

我正在使用一個漂亮的準系統expressjs應用程序,並希望添加庫/助手來存儲一些有用的代碼。理想情況下,我希望它能作爲一個模塊工作。但是,我無法讓它工作。這裏是我得到的:在expressjs中輕鬆使用助手類

// helpers/newlib.js 
var NewLib = function() { 
    function testing() { 
    console.log("test"); 
    } 
}; 

exports.NewLib = NewLib; 

// controllers/control.js 
var newlib = require('../helpers/newlib').NewLib; 
var helper = new NewLib(); 
helper.testing(); 

我得到的錯誤是ReferenceError: NewLib is not defined。基於我下載的另一個簡單模塊,我遵循了設計模式(如何工作的exports)。

我在做什麼錯?

回答

1

您的代碼有兩個問題。

首先,你分配NewLib功能從傭工/ newlib.jsnewlib變種,所以你應該使用new newlib()new NewLib()

// controllers/control.js 
var newlib = require('../helpers/newlib').NewLib; 
var helper = new newlib(); // <--- newlib, not NewLib 
helper.testing(); 

也可以將您的變量重命名爲NewLib

// controllers/control.js 
var NewLib = require('../helpers/newlib').NewLib; 
var helper = new NewLib(); // <--- now it works 
helper.testing(); 

其次,testing函數不能在構造函數的作用域之外訪問。例如,您可以通過將其指定爲this.testing來訪問它:

// helpers/newlib.js 
var NewLib = function() { 
    this.testing = function testing() { 
    console.log("test"); 
    } 
}; 
+0

完全工作。謝謝! – n0pe