TypeScript中与Java方法引用相对应的是:

huangapple go评论85阅读模式
英文:

TypeScript equivalent of Java method references

问题

我在TypeScript方面还是比较新手,但我对Java很了解。在Java中,每当需要满足函数式接口时,通常会使用lambda表达式(->)或方法引用(::)。

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

当目标是实现以下内容时:

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

有没有办法使用函数引用?以下这种方式似乎是错误的,因为send不会在this.listUpdateService的作用域中执行。(顺便问一下,它在哪个作用域中执行?)

this.entryService.getEntries()
  .subscribe(this.listUpdateService.send);
英文:

I'm sort of new to TypeScript, I know Java quite well though. There, whenever a functional interface needs to be satisfied, it's most commonly done using lambda expressions (->) or method references (::).

Lambda expressions seem to be equivalent between the two languages (correct me if I'm wrong). Is there a way to make use of method references?

When the goal is to achieve this:

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

Is there a way to use a function reference? The following way of doing it appears to be errorous, because send isn't executed in the scope of this.listUpdateService. (BTW, which scope is it executed in?)

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

答案1

得分: 2

你说得对,作用域不是 this.listUpdateService

如果你想保持正确的作用域,通常会使用 bind

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

这里有一个示例 playground

英文:

You are right, the scope is not this.listUpdateService.

If you want to stick the correct scope, you normally use bind.

<!-- language: typescript -->

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

Here is an example playground

huangapple
  • 本文由 发表于 2020年10月5日 13:30:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/64202917.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定