Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class methods in node.js

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.

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

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'
like image 389
Patrick Avatar asked Aug 02 '12 17:08

Patrick


People also ask

What is a method in class in JS?

Class methods are created with the same syntax as object methods. Use the keyword class to create a class. Always add a constructor() method.

What is class and its methods?

Definition. A class is a template for creating or instantiating objects within a program while a method is a function that exposes the behavior of an object. Thus, this is the main difference between class and method.

What is class function method?

The classmethod() is an inbuilt function in Python, which returns a class method for a given function.; Syntax: classmethod(function) Parameter :This function accepts the function name as a parameter. Return Type:This function returns the converted class method.


1 Answers

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

// 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);
like image 130
Dominic Barnes Avatar answered Oct 31 '22 23:10

Dominic Barnes