2017-04-23 41 views
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

控制檯日誌確實顯示對象的屬性和值。

如何從「結果」對象中提取「文本」屬性的局部值到全局範圍?

+0

重新標記爲這與TypeScript無關 –

回答

0

使用window,而不是this

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

不知道太多關於打字稿,但我猜測,它的使用strict mode,其中this是不確定的,而不是默認全局window對象,如果不用於類實例的上下文中。

+0

由此由假定頂層聲明的變量和函數;如果你不在全局範圍內工作,只需省略'window.',它將引用你所在的任何封閉範圍。 –