简体   繁体   English

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

[英]Typescript global variables becoming undefined after function call

In my code, I have two global variables defined as 在我的代码中,我有两个全局变量定义为

constructor() {
        this.map = new Map();
        this.player = new Player([], "");
    }

I can access these variables through my program normally, however when I call one of my functions this.handleInput(Command.GO, "north"); 我可以通过程序正常访问这些变量,但是当我调用函数之一this.handleInput(Command.GO, "north"); where Command.GO translates to "GO" and "north" is a direction to go to, all of my global variables become undefined. 在Command.GO转换为“ GO”而“ north”是一个方向的地方,我所有的全局变量都变得不确定。 In the handleInput method, 在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));
            }      
        }

I immediately get errors that this.player and this.map are undefined, however they were not undefined before I called the method! 我立即收到错误,指出this.player和this.map是未定义的,但是在调用该方法之前,它们并不是未定义的! Is there something about global variables in TS/JS that I'm not grasping? 我不了解TS / JS中关于全局变量的某些信息吗?

Your this is most likely referring to another object depending on how handleInput is being called. this是最有可能涉及到另一个对象取决于如何handleInput被调用。 In your contructor() , either bind handleInput to this or change your handleInput to use arrow function: 在你的contructor()或者bind handleInputthis或更改handleInput使用箭头功能:

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

Or: 要么:

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

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

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