Skip to content
Advertisement

variable defined in one function and undefined in other typescript

I have the following code:

class Currency {
    private counter = document.getElementById('counter');
    private dust = 0;
    private books = 0;
    private bookCounter = document.getElementById("books");
    
    constructor() {
        console.log("test")
        document.getElementById("bookbuy").addEventListener("click", this.buyBook)
    }

    public count() {
        this.dust ++;
        this.counter.innerHTML = "You have " + this.dust + " dust";
        console.log(this.dust)
    }

    public buyBook() {
        if (this.dust >= 10) {
            console.log("if works");
            this.dust - 10;
            this.books ++;
            this.counter.innerHTML = "You have " + this.dust + " dust";
            this.bookCounter.innerHTML = "You have " + this.books + " books";
        } else {
            console.log(this.dust)
        }
    }
  }

window.addEventListener("load", init);
function init(): void {
    const currency = new Currency();
    setInterval(() => {currency.count();}, 1000);
} 

the console.log in count() is defined and working fine, but when i try to use this.dust in buyBook() it returns as undefined. Why is this and how do I fix it?

Advertisement

Answer

You want to bind the this context for buyBook, or the event handler will redefine the this context.

Edit: Also, I think you meant to decrement 10 from this.dust not just subtract 10

class Currency {
    private counter = document.getElementById('counter');
    private dust = 0;
    private books = 0;
    private bookCounter = document.getElementById("books");
    
    constructor() {
        console.log("test")
        document.getElementById("bookbuy").addEventListener("click", this.buyBook.bind(this))
    }

    public count() {
        this.dust ++;
        this.counter.innerHTML = "You have " + this.dust + " dust";
        console.log(this.dust)
    }

    public buyBook() {
        if (this.dust >= 10) {
            console.log("if works");
            this.dust -= 10;
            this.books ++;
            this.counter.innerHTML = "You have " + this.dust + " dust";
            this.bookCounter.innerHTML = "You have " + this.books + " books";
        } else {
            console.log(this.dust)
        }
    }
  }

window.addEventListener("load", init);
function init(): void {
    const currency = new Currency();
    setInterval(() => {currency.count();}, 1000);
} 
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement