переменная, определенная в одной функции и неопределенная в другом typescript

#javascript #typescript #this

#javascript #typescript #это

Вопрос:

У меня есть следующий код:

 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);
} 
 

консоль.функция log in count() определена и работает нормально, но когда я пытаюсь использовать this.dust в buyBook(), она возвращает значение undefined .
Почему это и как мне это исправить?

Комментарии:

1. В this контексте buyBook when вызывается как обработчик события click for bookbuy , будет bookbuy элементом, а не вашим классом.

2. Вы можете изменить ее, обернув вызов метода, чтобы сохранить контекст. .addEventListener("click", () => this.buyBook())

Ответ №1:

Вы хотите привязать контекст this для buyBook, или обработчик событий переопределит этот контекст.

Редактировать: Кроме того, я думаю, вы хотели уменьшить 10 this.dust , а не просто вычесть 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);
}