javascript - 函数调用后 Typescript 全局变量变得未定义

标签 javascript typescript

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

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 handleInputthis 或更改您的 handleInput使用箭头功能:

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

或者:

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

关于javascript - 函数调用后 Typescript 全局变量变得未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48491949/

相关文章:

javascript - 仅针对一种表单的单一 onChange

javascript - 即使使用 return 语句,带有 forEach 的函数也会返回 undefined

javascript - Jquery 菜单悬停时从屏幕底部向上滑动

typescript - Angular 2 测试版 : Visual Studio ASP . NET MVC

javascript - 时刻格式详细日期作为日期对象

Angular订阅方法被多次调用

javascript - 获取内容可编辑插入符位置

javascript - 将类中某个 HTMLElement 成员的 onclick 属性设置为同一个类的方法

typescript - 如何将 autoprefixer 与 web 组件(litElement)一起使用?

javascript - 1980 年前和 1980 年后的 RegEx Vin 验证