如何从打字稿中的for-of循环访问this
变量?这是我的循环示例:
//for each author qs param
for (let author of qsParams.authors)
{
//check for match by id
var matches = this.vm.Authors.filter(x => x.id == author);
//if no match then continue
if (matches.length == 0) continue;
//select author
this.authorSelected(matches[0]);
}
this
关键字无法按预期访问父类。我做了一个基本的谷歌,但没有找到在一个for-for循环中获取this
句柄的答案。
更新
我可以在for-of循环上面添加以下引用,但它似乎有点hacky:
var that = this;
//for each author qs param
for (let author of qsParams.authors)
{
//check for match by id
var matches = that.vm.Authors.filter(x => x.id == author);
//if no match then continue
if (matches.length == 0) continue;
//select author
that.authorSelected(matches[0]);
}
你有比var that=this
更优雅的方式;或者这没有更好的方法吗?
答案 0 :(得分:-2)
问题不在于你有一个for/of
循环。问题是包含方法是从其this
丢失的上下文中调用的。请参阅有关this
的数百个其他TypeScript问题之一,了解如何避免这种情况发生。