Javascript node.js中的类方法

Javascript node.js中的类方法,javascript,node.js,design-patterns,Javascript,Node.js,Design Patterns,在过去的一个小时里,我一直在尝试使用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

在过去的一个小时里,我一直在尝试使用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

在不创建用户对象/实例的情况下,如何使用这些函数创建适当的模块

更新

我回顾了提议的解决方案:

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'
您需要在某个时候
新用户(db)

您可以创建一个init方法

exports.init = function(db){
  return new User(db)
}
然后从您的代码:

var User = require(...).init(db);

这里发生了几件事,我已经更正了您的源代码,并添加了注释来解释:

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;
// 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);
app.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;
// 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);

是的,从技术上说他刚导入了课堂参考。。。没有实例化。嗯,好的。我希望我能绕过一个例子。这似乎是最好的解决办法。谢谢不客气。如果我没弄错的话,Java人会把它叫做工厂。不过,似乎有些库在没有实例的情况下做到了这一点。我更新了这个问题,这个解决方案还不太管用。你不必去做新的“类”,如果你不需要多个特定代码的实例,你可以使用模块化的方法。只有exports.myFunction=function(){…}。此外,您还没有得到我的第一个解决方案。如果有帮助,请参阅中的答案,其中显示了如何创建一个可以访问类方法的Express中间件函数。此答案假设ES6课程可用。