这将导致以下错误: Cannot read property 'length' of undefined
const msg$ = new Subject<string>();
msg$.subscribe(console.log)
of("Hello").subscribe(msg$.next);
但是,如果我将msg $ .next包装在一个函数中,则它可以正常工作而没有任何错误。
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陷阱我在这里工作时并不了解。
为了后代的缘故接受了答案
我认为这个问题归结为“将函数作为参数传递时,“ this”的值是什么?”。你可能会在这里找到一些答案。如何在回调中访问正确的答案?。
this
在你的第一个示例中具有错误的值。如果放入console.log(this)
内部nextMsg
,则会看到SafeSubscriber
缺少observers.length
被访问的属性。Subject#next
rxjs6中的函数依赖于此为Subject
具有observers.length
属性的
是的,当然。似乎很傻,我没注意到。msg$.next.bind(msg$)
作品。
obj.func
没有obj
上下文,而obj.func()
有。