【发布时间】:2018-06-09 16:11:14
【问题描述】:
我正在编写一个简单的文字游戏来练习我的 javascript(我是新手),使用 NPM 包 prompt (https://www.npmjs.com/package/prompt) 在我需要回复时查询用户。
由于我来自 OOP 背景(使用其他语言),我一直在尝试将不同的功能封装在不同的对象中。所以我在一个对象中拥有所有prompt 相关代码,就像这样
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);
};
}
和像这样的另一个对象中的游戏逻辑(这是代码的相关部分)
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();
};
}
然后我就这样开始游戏
const game = new Game();
game.init();
game.startGame();
我遇到的问题是在Game 方法storeUserName 中,我作为回调传递给prompt,我无法通过this 访问Game 对象,因此,当我打电话时
this.doNextRound
在storeUserName我明白了
TypeError: this.doNextRound is not a function
我明白为什么,因为this 指的是回调中的节点。但我不知道如何在我作为回调传递的方法中保留对正确this 的引用。我了解如何在更“香草”的 Javascript 中做到这一点——使用 that = this 或 apply 等,但我不确定在 Node 回调中处理 this 的最佳方法是什么时候通过另一个对象的方法。非常感谢任何建议。
【问题讨论】:
-
谁标记了这个重新打开应该解释为什么它应该被重新打开。投票保持关闭。
标签: javascript node.js callback this