Warm tip: This article is reproduced from serverfault.com, please click

javascript-下一个主题调用导致奇怪的错误

(javascript - Subject call to next causing a strange error)

发布于 2020-12-01 16:02:54

这将导致以下错误: Cannot read property 'length' of undefined

const msg$ = new Subject<string>();
msg$.subscribe(console.log)
of("Hello").subscribe(msg$.next);

但是,如果我将msg $ .next包装在一个函数中,则它可以正常工作而没有任何错误。

  • Lambda函数
const msg$ = new Subject<string>();
msg$.subscribe(console.log)
of("Hello").subscribe(greeting => msg$.next(greeting));
  • 匿名功能
const msg$ = new Subject<string>();
msg$.subscribe(console.log)
of("Hello").subscribe(function(greeting){
  msg$.next(greeting);
});
  • 命名功能
function nextMsg(greeting){
  msg$.next(greeting);
}
const msg$ = new Subject<string>();
msg$.subscribe(console.log)
of("Hello").subscribe(nextMsg);

它们全都是包装函数,似乎只调用下一个函数。这里发生了什么?好像有一个JavaScript陷阱我在这里工作时并不了解。

Questioner
Mrk Sef
Viewed
11
Mrk Sef 2020-12-22 04:33:21

为了后代的缘故接受了答案


我认为这个问题归结为“将函数作为参数传递时,“ this”的值是什么?”。你可能会在这里找到一些答案。如何在回调中访问正确的答案

this在你的第一个示例中具有错误的值。如果放入console.log(this)内部nextMsg,则会看到SafeSubscriber缺少observers.length被访问的属性Subject#nextrxjs6中函数依赖于此为Subject具有observers.length属性的

是的,当然。似乎很傻,我没注意到。msg$.next.bind(msg$)作品。

obj.func没有obj上下文,而obj.func()有。