[英]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. count() 中的 console.log 已定义并且工作正常,但是当我尝试在 buyBook() 中使用 this.dust 时,它返回未定义。 Why is this and how do I fix it?
为什么会这样,我该如何解决?
You want to bind the this context for buyBook, or the event handler will redefine the this context.您想为 buyBook 绑定 this 上下文,否则事件处理程序将重新定义 this 上下文。
Edit: Also, I think you meant to decrement 10 from this.dust
not just subtract 10编辑:另外,我认为你的意思是从
this.dust
中减去 10 而不仅仅是减去 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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.