1

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?

2
  • How is handleInput being called Commented Jan 28, 2018 at 22:21
  • 1
    How exactly do you call handleInput? Also try console.log(this) inside the method to see what's going wrong… Commented Jan 28, 2018 at 22:24

1 Answer 1

3

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 => {}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.