0

How can I access this variable from a for-of loop in typescript? Here's my sample 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 this keyword does not have access to the parent class as expected. I did a basic google but did not find the answer for getting a handle to this within a for-of loop.

UPDATE

I could add the following reference above the for-of loop but it seems kind 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]);
    }  

Do you have a more elegant way than var that=this; or is this there no better way?

Z.Lin
  • 28,055
  • 6
  • 54
  • 94
user8570495
  • 1,645
  • 5
  • 19
  • 29
  • There should be no issue with `this` in the code you show. Please edit your question into a [mcve] that shows the problem. – Louis Sep 07 '17 at 20:36
  • this will target the object of an class instance. It depends what class/function this for loop is embedded in – wheeler Sep 07 '17 at 20:36
  • Edited question is still not sufficient to reproduce the problem – Ryan Cavanaugh Sep 10 '17 at 22:50
  • Possible duplicate of [Preserving a reference to "this" in JavaScript prototype functions](https://stackoverflow.com/questions/2025789/preserving-a-reference-to-this-in-javascript-prototype-functions) – Louis Oct 24 '17 at 17:36

1 Answers1

-2

The problem is not that you have a for/of loop. The problem is that the containing method was called from a context where its this was lost. See one of the hundreds of other TypeScript questions about this for how to have this not happen.

Ryan Cavanaugh
  • 209,514
  • 56
  • 272
  • 235