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 !
thisno longer comes from the class when you pass the function torouter.get. Convert yourlistto an arrow function and it will workrouter.get('/', user.list.bind(this));router.get('/', user.list.bind(this));I getInstantiated id:undefinedid:undefined? You don't even have anid. Check for typo'sconsole.log("Instantiated id:" + this._id)