javascript – 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'

如何创建具有这些功能的正确模块,而不创建用户的对象/实例?

更新

我提出了解决方案:

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,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,callback);

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...