node.js中的类方法
我一直在尝试在最后一个小时用findOne,findOneOrCreate等方法为passport.js编写一个用户模块,但是不能正确使用它。
user.js的
var User = function(db) { this.db = db; } User.prototype.findOne(email, password, fn) { // some code here } module.exports = exports = User;
app.js
User = require('./lib/User')(db); User.findOne(email, pw, callback);
我经历了几十个错误,主要是
TypeError: object is not a function
要么
TypeError: Object function () { function User(db) { console.log(db); } } has no method 'findOne'
如何用这些函数创build一个合适的模块而不创build用户的对象/实例?
更新
我解决了所提出的解决scheme:
var db; function User(db) { this.db = db; } User.prototype.init = function(db) { return new User(db); } User.prototype.findOne = function(profile, fn) {} module.exports = User;
没有运气。
TypeError: Object function User(db) { this.db = db; } has no method 'init'
一些事情正在发生,我已经纠正了你的源代码,并添加了一些注释来解释:
LIB / user.js的
// much more concise declaration function User(db) { this.db = db; } // You need to assign a new function here User.prototype.findOne = function (email, password, fn) { // some code here } // no need to overwrite `exports` ... since you're replacing `module.exports` itself module.exports = User;
app.js
// don't forget `var` // also don't call the require as a function, it's the class "declaration" you use to create new instances var User = require('./lib/User'); // create a new instance of the user "class" var user = new User(db); // call findOne as an instance method user.findOne(email, pw, callback);
你需要new User(db)
在某个时刻。
你可以做一个init方法
exports.init = function(db){ return new User(db) }
然后从你的代码:
var User = require(...).init(db);