I am receiving an error while trying to access a private function inside another function
class GameController {
public async cardShuffle (req: Request, res: Response): Promise<void> {
other code here...
const treatment = this.cardTreatment(shuffledCards)
console.log(treatment)
})
}
private cardTreatment (cards: Array<String | Number>): Array<String | Number> {
return cards
}
}
export default new GameController()
Error:
(node:2645) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'cardTreatment' of undefined
CodePudding user response:
The issue is not that the function is private, but that this
is undefined
in the context you called it. For example, you may have done const shuffle = controller.cardShuffle; shuffle()
.
See below:
class Example {
foo() {
return this.bar();
}
bar() {
return 'It works!';
}
}
const test = new Example();
console.log(test.foo())
const foo = test.foo;
try {
console.log(foo())
} catch(e) {
console.log('Doesnt work');
}
console.log(foo.call(test))