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");
where Command.GO translates to "GO" and "north" is a direction to go to, all of my global variables become undefined. In the handleInput method,
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! Is there something about global variables in TS/JS that I'm not grasping?
Your this
is most likely referring to another object depending on how handleInput
is being called. In your contructor()
, either bind
handleInput
to this
or change your handleInput
to use arrow function:
constructor() {
this.handleInput = this.handleInput.bind(this);
}
Or:
handleInput = (cmd:Command, arg:string):boolean => {}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.