Reputation: 484
So I have a class with functions where one is dependent on another. This class is exported with module. According to anything I can find I should be able to use "this" but that throws an error.
Example:
class Test{
test(){
console.log('hello');
}
dependentMethod(){
this.test();
}
}
module.exports = Test;
This however throws these errors in node:
(node:69278) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: Cannot read property 'test' of undefined
(node:69278) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
(node:69278) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): TypeError: Cannot read property 'test' of undefined
It will work fine if I put the function outside the class though. Can anyone explain why this fails? :)
EDIT:
This is the code in server.js (simplified for the example) that uses the class:
const test = require(__dirname + '/server/Test');
const validator = async function(req, res, next){
const test = new test();
const serverTest = await test.dependentMethod();
next();
};
app.get('/Response/:id/:is/:userId/:hash', validator, async function (req, res, next) {
//does smth
}
Used seperately does not work either
const test = new Test();
app.get('/Response/:id/:is/:userId/:hash', Test.dependentMethod, async function (req, res, next) {
//Same error
}
Upvotes: 0
Views: 9516
Reputation: 277
class Test{
test(){
console.log('hello');
}
let dependentMethod = ()=>{
this.test();
}
}
module.exports = Test;
either manually bind this or use arrow functions which will bind this
to the class object
Upvotes: 3
Reputation: 762
Man, you're not showing you real code to us.
I feel that in real life you are using test.dependentMethod
as middleware. And it aclually is using standalone function loosing the context. Thats's why you have an error Cannot read property 'test' of undefined
.
The solution is either using test.dependentMethod.bind(test)
or the code from your Edit section, where you created separate validator function and using class instances correctly.
Upvotes: 1
Reputation: 4200
Working as expected.
Take a look here. You just need to rectify some syntactic errors.
Test.js
class Test{
test(){
console.log('hello');
}
dependentMethod(){
this.test();
}
}
module.exports = Test;
Test1.js
const fileR = require('./Test.js');
const validator = async function(){
const fr = new fileR();
const serverTest = await fr.dependentMethod();
};
validator();
Output:
> hello
Upvotes: 6