Search code examples
javascriptlexical-scopedynamic-scope

How to manipulate variable scope?


Learning some TypeScript. Trying to make this bit of code work:

...
ocrText: string;
...
foo() {
    Tesseract.recognize(<Tesseract.ImageLike>document.getElementById('image'))
       .then(function(result) {
            console.log(result);
            this.ocrText = result.text;
       });
}

Getting this error: Uncaught TypeError: Cannot set property 'ocrText' of undefined

The console log does show the object properties and values.

How do I extract the local value of the 'text' property from the 'result' object to a global scope?


Solution

  • Use window instead of this:

    var Text = '';
    (()=> fetch('www.example.com')
     .then(response => response.text())
     .then(text => window.Text=text))();
    

    Don't know too much about typescript, but I'm guessing that it's using strict mode, where this is undefined instead of defaulting to the global window object if not used in the context of a class instance.