我正在写一个简单的文字游戏来练习我的javascript (我是新手),当我需要一个响应时,使用NPM package 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();
我遇到的问题是,在我作为回调传递给prompt
的Game
方法storeUserName
中,我无法通过this
访问Game
对象,因此,当我调用
this.doNextRound
在storeUserName
内部,我得到了
TypeError: this.doNextRound is not a function
我理解其中的原因,因为this
在回调中引用了节点。但是我不知道如何在作为回调传递的方法中保持对正确this
的引用。我知道如何在更“普通”的Javascript中做到这一点--使用that = this
或apply
等,但我不确定当你传递另一个对象的方法时,在节点回调中处理this
的最好方法是什么。任何建议都非常感谢。
发布于 2018-06-10 00:16:37
this.prompter.getUserName(this.storeUserName.bind(this));
或者是一个arrow function
this.prompter.getUserName( _ => this.storeUserName() );
这两种方法都不会起作用。
https://stackoverflow.com/questions/50776174
复制相似问题