我正在创建一个对象(一个虚拟的 http 响应对象),如下所示:
res = {
body : '',
write : (text : string) => {
this.body = this.body + text;
},
end : () => {}
};
但是 typescript 编译器给出错误:
error TS2108: 'this' cannot be referenced within module bodies.
我知道这在 JavaScript 中是可能的(在对象内部有 this
),如何在 TypeScript 中实现这一点?
最佳答案
您可以通过将箭头函数 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).
关于javascript - 如何在 typescript 中创建具有函数和数据的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25562658/