javascript - 如何在 typescript 中创建具有函数和数据的对象?

标签 javascript node.js typescript

我正在创建一个对象(一个虚拟的 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/

相关文章:

javascript - 如何使用 Jquery 在特定时间后自动销毁 DOM 元素

angular - 在 FormGroup 中使用 [(ngModel)]

javascript - JavaScript new Date() 使用什么时区?

javascript - 跟踪在页面上显示某些元素所花费的时间

javascript - 图表数据缩放无法读取未定义的属性 'length'

javascript - 子进程收不到消息

javascript - 防止在表单提交/Node 后重新加载页面(没有可用的 ajax)

typescript block 节点/模块工厂模式 : error TS4060

JavaScript 时间积分

javascript - C 语言开发人员未能利用的 JavaScript 特性?