如何解决具有不同值的打字稿变量
我正在将TypeScript与ES6一起使用
看看下面的代码:
private latestPrices: any = {};
public constructor() {
this.timer = global.setInterval(this.getPricesCallback,1500);
}
private getPricesCallback() {
// tslint:disable-next-line:no-console
console.log("Hello");
// tslint:disable-next-line:no-console
console.log(this.latestPrices);
this.latestPrices = { "bookname ":"VB BLACK BOOK","price":500 };
// tslint:disable-next-line:no-console
console.log(this.latestPrices);
}
public getLatestPrices()
{
// tslint:disable-next-line:no-console
console.log(this.latestPrices);
return this.latestPrices;
}
输出为:
Hello
{ "bookname ":"VB BLACK BOOK","price":500 }
{ "bookname ":"VB BLACK BOOK","price":500 }
每1.5秒一次……到目前为止一切顺利。但是每次我叫“ getLatestPrices”时,我只会得到:
{}
这是为什么? 我现在看不到问题。
谢谢您的帮助。
解决方法
这是具有范围界定的经典js陷阱。
this
中的getPricesCallback
自变量在通过setinterval回调时指向另一个上下文,因此它在此处设置了lastPrices
属性。
更改global.setInterval(this.getPricesCallback,1500);
到global.setInterval(this.getPricesCallback.bind(this),1500);
或global.setInterval(() => this.getPricesCallback(),1500);
应该可以解决问题。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。