繁体   English   中英

函数调用后,Typescript全局变量变得不确定

[英]Typescript global variables becoming undefined after function call

在我的代码中,我有两个全局变量定义为

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中关于全局变量的某些信息吗?

this是最有可能涉及到另一个对象取决于如何handleInput被调用。 在你的contructor()或者bind handleInputthis或更改handleInput使用箭头功能:

constructor() {
  this.handleInput = this.handleInput.bind(this);
}

要么:

handleInput = (cmd:Command, arg:string):boolean => {}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM