2

I don't quite understand how class inheritance and context is working in nodejs + expressjs.

I have 3 files :

api.js

class API {
  constructor () {
    this._id = Math.random()
    console.log("Instantiated id:" + this._id)
  }

  list (req, res, next) {
    console.log("Instantiated id:" + this._id)
  }
}
module.exports = API

user.js

const API = require('./api.js')

class UserAPI extends API {

  constructor () {
    super()
  }
}
module.exports = UserAPI

route.js

var UserAPI = require('./user.js')
var user = new UserAPI()
router.get('/', user.list);

What I would like to see is the ID when starting then the same ID each time I do a GET request. But when I do a GET request I have : ERROR: TypeError: Cannot read property '_id' of undefined

How can I have access to member in the Base class when deriving it ?

Thanks !

5
  • Classes are syntactic sugar for JS's prototypal inheritance. I your case this no longer comes from the class when you pass the function to router.get. Convert your list to an arrow function and it will work Commented Oct 11, 2017 at 12:13
  • Or router.get('/', user.list.bind(this)); Commented Oct 11, 2017 at 12:15
  • When I change to router.get('/', user.list.bind(this)); I get Instantiated id:undefined Commented Oct 11, 2017 at 12:24
  • id:undefined? You don't even have an id. Check for typo's Commented Oct 11, 2017 at 12:31
  • It's just the line of text in the console.log: console.log("Instantiated id:" + this._id) Commented Oct 11, 2017 at 12:33

2 Answers 2

2

The problem is not class inheritance, but simply the way you use the list method. You are passing it directly to router.get, that won't work, because you are only passing a reference to the function, which then doesn't know the context of the instance of UserAPI.

You can fix this by passing an anonymous function to router.get that then executes user.list, like this:

route.js

var UserAPI = require('./user.js')
var user = new UserAPI()
router.get('/', (req, res, next) => user.list(req, res, next));
Sign up to request clarification or add additional context in comments.

Comments

0

Making API inheritance with express is impossible. CheckZinkyJS, it makes exactly what you want to do.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.