Javascript 函数调用后Typescript全局变量变得未定义
在我的代码中,有两个全局变量定义为Javascript 函数调用后Typescript全局变量变得未定义,javascript,typescript,Javascript,Typescript,在我的代码中,有两个全局变量定义为 constructor() { this.map = new Map(); this.player = new Player([], ""); } 我通常可以通过我的程序访问这些变量,但是当我调用我的函数之一this.handleInput(Command.GO,“north”)当Command.GO转换为“GO”且“north”是一个方向时,我的所有全局变量都未定义。在handleInput方法中 private h
constructor() {
this.map = new Map();
this.player = new Player([], "");
}
我通常可以通过我的程序访问这些变量,但是当我调用我的函数之一this.handleInput(Command.GO,“north”)代码>当Command.GO转换为“GO”且“north”是一个方向时,我的所有全局变量都未定义。在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中的全局变量有什么我没有掌握的吗?您的
这
很可能是指另一个对象,具体取决于调用handleInput
的方式。在您的constructor()
中,将绑定handleInput
到此或更改handleInput
以使用箭头函数:
constructor() {
this.handleInput = this.handleInput.bind(this);
}
或:
如何调用handleInput
您究竟如何调用handleInput
?还可以在方法内部尝试console.log(this)
,查看出了什么问题…
handleInput = (cmd:Command, arg:string):boolean => {}