Pat*_*ick 11 javascript design-patterns node.js
我一直在尝试用lastOne,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;
Run Code Online (Sandbox Code Playgroud)
app.js
User = require('./lib/User')(db);
User.findOne(email, pw, callback);
Run Code Online (Sandbox Code Playgroud)
我经历过几十个错误
TypeError: object is not a function
Run Code Online (Sandbox Code Playgroud)
要么
TypeError: Object function () {
function User(db) {
console.log(db);
}
} has no method 'findOne'
Run Code Online (Sandbox Code Playgroud)
如何在不创建User对象/实例的情况下使用这些函数创建合适的模块?
更新
我讨论了提出的解决方案:
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;
Run Code Online (Sandbox Code Playgroud)
没运气.
TypeError: Object function User(db) {
this.db = db;
} has no method 'init'
Run Code Online (Sandbox Code Playgroud)
Dom*_*nes 16
这里有几件事情,我已经更正了你的源代码并添加了注释来解释:
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;
Run Code Online (Sandbox Code Playgroud)
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);
Run Code Online (Sandbox Code Playgroud)
你需要new User(db)在某个时候.
你可以制作一个init方法
exports.init = function(db){
return new User(db)
}
Run Code Online (Sandbox Code Playgroud)
然后从你的代码:
var User = require(...).init(db);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17939 次 |
| 最近记录: |