I'm writing a simple word game to practice my javascript (I'm new to it) using the NPM package prompt
(https://www.npmjs.com/package/prompt) to query the user when I need a response.
Since I come from an OOP background (in other languages) I've been experimenting with encapsulating different functionalities in different objects. So I have all the prompt
related code in one object, like this
function Prompter() {
this.getUserName = function (callback) {
var schema = {
properties: {
name: {
description: "Tu nombre por favor:",
pattern: /^[ñÑa-zA-Z\s\-]+$/,
message: 'Solo letras, por favor',
required: true
}
}
};
prompt.get(schema, callback);
};
}
and game logic in another object like this (this is the relevant part of the code)
function Game() {
this.qGenerator = null;
this.prompter = null;
this.user = "";
this.doNextRound = function () {
//// omitted for brevity
};
this.init = function () {
this.qGenerator = new QuestionGenerator();
this.prompter = new Prompter();
};
this.startGame = function () {
this.prompter.getUserName(this.storeUserName);
};
this.storeUserName = function (err, result) {
if (err) {
this.handleErr(err);
return;
}
this.user = result.name;
this.doNextRound();
};
}
and I start the game like this
const game = new Game();
game.init();
game.startGame();
The problem I have is that in the Game
method storeUserName
, which I've passed as a callback to prompt
, I have no access to the Game
object through this
, and thus, when I call
this.doNextRound
inside of storeUserName
I get
TypeError: this.doNextRound is not a function
I understand why, as this
refers to Node inside the callback. But I don't know how to keep a reference to the correct this
inside the method I'm passing as callback. I understand how to do it in more 'vanilla' Javascript -- using that = this
, or apply
,etc, but I'm not sure what the best way to handle this
inside Node callbacks is when you're passing another object's methods. Any advice much appreciated.