【问题标题】:How to create an object with functions and data in typescript?如何在打字稿中创建具有函数和数据的对象?
【发布时间】:2014-10-23 03:12:44
【问题描述】:

我正在创建一个对象(一个虚拟的 http 响应对象),如下图所示:

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

但是打字稿编译器报错:

错误 TS2108:不能在模块主体中引用“this”。

我知道这在 javascript 中是可能的(在对象内部有 this),如何在 typescript 中实现这一点?

【问题讨论】:

    标签: javascript node.js typescript


    【解决方案1】:

    您可以通过将箭头函数write 更改为标准函数来完成它,然后它将像通常在普通 JavaScript 中一样工作。

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

    这是因为箭头函数如何改变this 在其中的工作方式。很好描述here

    标准函数(即使用 function 关键字编写)将 动态绑定 this 取决于执行上下文(就像在 JavaScript),另一方面,箭头函数保留 封闭上下文。这是一个有意识的设计决策,如箭头 ECMAScript 6 中的函数旨在解决一些问题 与动态绑定 this 相关联(例如,使用函数调用 模式)。

    【讨论】:

      【解决方案2】:

      在大卫提交(正确)答案之前,我设法想出了一个解决方法。它没有回答我自己的问题,但它是一个可能的解决方案。

      创建class Response:

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

      然后将res 设为Response 类型的对象:

      res = new Response();
      

      【讨论】:

        猜你喜欢
        • 2019-06-21
        • 2016-07-19
        • 1970-01-01
        • 2018-10-27
        • 1970-01-01
        • 1970-01-01
        • 2019-04-29
        • 2021-05-21
        • 2021-12-17
        相关资源
        最近更新 更多