-1

The method foo gets some HTML elements using JQuery and do some stuff in a loop with them. Another method bar, returns some value based on the input from method foo. In the loop, this means a particular HTML element of the list obviously.

Out of the loop, this represents the current class. I can call any method in this class. But in the loop it represents the HTML element.

My question is, how can I call bar() without using this

    foo(source: Source[] | undefined){
       let codeLines: JQuery<HTMLElement> = $('.source');
       codeLines.each(function (index) {
           this.bar(this.innerHTML); //this line throws the **error**.
       });
    }

    bar(innerHTML: string){
       return 0;
    }

The error is,

TS2339: Property 'bar' does not exist on type 'HTMLElement'
Cahi
  • 1

1 Answers1

0

Capture the outer this in a variable.

foo(source: Source[] | undefined){
    let thisCapture = this;
   let codeLines: JQuery<HTMLElement> = $('.source');
   codeLines.each(function (index) {
       thisCapture.bar(this.innerHTML); //this line throws the **error**.
   });
}

bar(innerHTML: string){
   return 0;
}
bcr666
  • 2,157
  • 1
  • 12
  • 23