英文:
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));
英文:
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));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论