0

学习一些 TypeScript。试图使这段代码工作:

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

收到此错误:Uncaught TypeError: Cannot set property 'ocrText' of undefined

控制台日志确实显示了对象属性和值。

如何从“结果”对象中提取“文本”属性的本地值到全局范围?

4

1 回答 1

0

使用window代替this

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

对打字稿不太了解,但我猜它使用的是严格模式,如果不在类实例的上下文中使用,则wherethis是 undefined 而不是默认为全局对象。window

于 2017-04-23T04:07:46.987 回答