2014-08-29 37 views
0

我建立如下所示的對象(虛擬HTTP響應對象):如何用打字稿中的函數和數據創建對象?

res = { 
    body : '', 
    write : (text : string) => { 
     this.body = this.body + text; 
    }, 
    end :() => {} 
}; 

但打字稿編譯器是給錯誤:

error TS2108: 'this' cannot be referenced within module bodies.

我知道這是可能的(具有this內部對象)在JavaScript中,如何在打字稿中完成此操作?

回答

2

您可以通過將箭頭功能write更改爲標準功能來實現它,然後它將像普通的JavaScript一樣工作。

res = { 
    body : '', 
    write : function(text: string) { 
     this.body = this.body + text; 
    }, 
    end :() => {} 
}; 

這是因爲箭頭函數如何改變this如何在它們內部工作。它很好地描述了here

Standard functions (ie. written using function keyword) will dynamically bind this depending on execution context (just like in JavaScript), arrow functions on the other hand will preserve this of enclosing context. This is a conscious design decision as arrow functions in ECMAScript 6 are meant to address some problems associated with dynamically bound this (eg. using function invocation pattern).

0

大衛提交的(正確)的答案之前,我設法想出了一個變通。它不回答我自己的問題,但它是一個可能的解決方案。

創建class Response

res = new Response(); 
Response

class Response { 
    body : string; 
    constructor() { 
     this.body = ''; 
    } 
    write(text : string) { 
     this.body = this.body + text; 
    } 
    end() {} 
} 

,然後作出一個res對象