javascript node.js 中的类方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11782453/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 14:19:52  来源:igfitidea点击:

Class methods in node.js

javascriptnode.jsdesign-patterns

提问by Patrick

I've been trying for the last hour to write a user module for passport.js with the findOne, findOneOrCreate, etc. methods, but can't get it right.

在过去的一个小时里,我一直在尝试使用 findOne、findOneOrCreate 等方法为passport.js 编写用户模块,但无法正确完成。

User.js

用户.js

var User = function(db) {
  this.db = db;
}

User.prototype.findOne(email, password, fn) {
  // some code here
}

module.exports = exports = User;

app.js

应用程序.js

User = require('./lib/User')(db);
User.findOne(email, pw, callback);

I've been through dozens of errors, mostly

我经历了几十个错误,主要是

TypeError: object is not a function

or

或者

TypeError: Object function () {
  function User(db) {
    console.log(db);
  }
} has no method 'findOne'

How do I create a proper module with these functions without creating an object/instance of User?

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

Update

更新

I went over the proposed solutions:

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

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;

No luck.

没有运气。

TypeError: Object function User(db) {
  this.db = db;
} has no method 'init'

回答by Dominic Barnes

A couple of things are going on here, I've corrected your source code and added comments to explain along the way:

这里发生了一些事情,我已经更正了您的源代码并添加了注释以在此过程中进行解释:

lib/User.js

库/用户.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

应用程序.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);

回答by 3on

You need to new User(db)at some point.

你需要new User(db)在某个时候。

You could make an init method

你可以做一个 init 方法

exports.init = function(db){
  return new User(db)
}

And then from your code:

然后从你的代码:

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