How can I retrieve the value of this
from a for-of loop in TypeScript? Check out this example for-of loop:
//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]);
}
The keyword this
is unable to access the parent class as anticipated. I searched online but couldn't find a solution for referencing this
within a for-of loop.
UPDATE
I came up with the workaround below, which involves adding the reference before the for-of loop:
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]);
}
Is there a more elegant way than using var that=this
; or is this the best approach?