简体   繁体   中英

Variable is always undefined when called in a function

Before I come to my question, here is my Typescript class:

export class Info {

    private currentId: number;

    private addToListButton: HTMLInputElement;

    constructor() {
        this.currentId = +(<HTMLInputElement> document.getElementById("Example")).value;

        this.addToListButton = <HTMLInputElement> document.getElementById("addToList");

        this.registerEvents();
    }

    private registerEvents(): void {
        this.addToListButton.addEventListener("click", (() => this.addToList()));
    }

    private addToList(): void {
        var data: SomeModel;
        data.id = this.currentId;

        // ajax stuff
    }
}

My problem is when I want to get the "currentId" for the model, it's always undefined. The other variable "addToListButton" can I use in the same function without problems.

I can't see what's the problem there.

Thanks for your help!

The keyword this in the function addToList doesn't refer to the instance of the class Info when the function is called here this.addToListButton.addEventListener("click", (() => this.addToList())); .

To have this refering to the instance, use an arrow function:

private const addToList = (): void => { // Arrow function
  var data: SomeModel;
  data.id = this.currentId;

  // ajax stuff
}

Here are some explanations on what arrow functions are.

In the addToList() method, the keyword this refers to the event context not the Info object context.

To use in this manner, you'll need to bind the method to the class. Add this to the constructor:

this.addToList = this.addToList.bind(this);

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.

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