在我的代码中,我有两个全局变量定义为
constructor() {
this.map = new Map();
this.player = new Player([], "");
}
我可以正常通过程序访问这些变量,但是当我调用我的函数之一时 this.handleInput(Command.GO, "north");
其中 Command.GO 翻译为“GO”而“北”是一个方向,我所有的全局变量都变得未定义。在handleInput方法中,
private handleInput(cmd:Command, arg:string):boolean {
console.log("Handling", cmd, "with argument '"+arg+"'");
if (cmd === "GO") {
console.log(`You go ${arg}`);
this.player.setCurrentLocation(this.map.getNextLocation(arg).getName());
this.updateGame(this.map.getNextLocation(arg));
}
}
我立即收到 this.player 和 this.map 未定义的错误,但在我调用该方法之前它们并不是未定义的! TS/JS 中的全局变量是否有一些我不明白的地方?
最佳答案
您的 this
很可能引用另一个对象,具体取决于 handleInput
的调用方式。在您的 constructor()
中,将 bind
handleInput
到 this
或更改您的 handleInput
使用箭头功能:
constructor() {
this.handleInput = this.handleInput.bind(this);
}
或者:
handleInput = (cmd:Command, arg:string):boolean => {}
关于javascript - 函数调用后 Typescript 全局变量变得未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48491949/