terpak
terpak

Reputation: 1151

Node.js: Referencing custom class within another custom class

I'm writing a web backend that has a User class. It also has an Attributes class which records user stats. However, I'm unsure how to reference the Attributes class within the User.js file. I'd want to be able to do this, more or less:

function User(id){
    this.attributes = new Attributes();
}

module.exports = User;

Upvotes: 0

Views: 48

Answers (1)

Nijikokun
Nijikokun

Reputation: 1524

Assuming you just want to call the other module...

var Attributes = require('/path/to/attributes.js')

function User (id) {
  this.id = id
  this.attributes = new Attributes()
}

module.exports = User

If you want to extend User

var Attributes = require('/path/to/attributes.js')

function User (id) {
  this.id = id
}

User.prototype = Object.create(Attributes.prototype);
User.prototype.constructor = Attributes;

module.exports = User

Now whatever methods Attributes has User will have, and you can do user instanceof Attributes

Upvotes: 1

Related Questions