【问题标题】:TypeScript equivalent of Java method referencesJava 方法引用的 TypeScript 等效项
【发布时间】:2020-10-05 05:30:42
【问题描述】:

我对 TypeScript 有点陌生,不过我对 Java 很了解。在那里,每当需要满足功能接口时,最常见的方法是使用 lambda 表达式 (->) 或方法引用 (::)。

Lambda 表达式在两种语言之间似乎是等价的(如果我错了,请纠正我)。有没有办法利用方法引用?

当目标是实现这一点时:

  this.entryService.getEntries()
    .subscribe(entries => this.listUpdateService.send(entries));

有没有办法使用函数引用?下面的做法似乎是错误的,因为send 没有在this.listUpdateService 的范围内执行。 (顺便说一句,它在哪个范围内执行?)

  this.entryService.getEntries()
    .subscribe(this.listUpdateService.send);

【问题讨论】:

    标签: java typescript lambda scope method-reference


    【解决方案1】:

    你是对的,范围不是this.listUpdateService

    如果你想坚持正确的范围,你通常使用bind

    this.entryService.getEntries()
      .subscribe(this.listUpdateService.send.bind(this.listUpdateService));
    

    Here is an example playground

    【讨论】:

      猜你喜欢
      • 2016-06-12
      • 2019-02-07
      • 1970-01-01
      • 1970-01-01
      • 2017-12-22
      • 1970-01-01
      • 2012-01-21
      • 1970-01-01
      • 2016-05-17
      相关资源
      最近更新 更多