Reputation: 35
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 !
Upvotes: 2
Views: 1026
Reputation: 471
Making API inheritance with express is impossible. CheckZinkyJS, it makes exactly what you want to do.
Upvotes: 0
Reputation: 20246
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));
Upvotes: 2