这会导致以下错误:Cannot read property 'length' of undefinedconst 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 陷阱。
1 回答

互换的青春
TA贡献1797条经验 获得超6个赞
为了后代而接受的答案
我认为这个问题归结为“当将函数作为参数传递时,“this”的值是什么?”。
this
在您的第一个示例中具有错误的值。如果你把 a 放在console.log(this)
里面nextMsg
,你会发现它缺少被访问的SafeSubscriber
属性。observers.length
rxjs6 中的函数Subject#next
依赖 this 成为Subject
具有observers.length
属性的 a
是的,当然。看来我很愚蠢,我没有注意到。msg$.next.bind(msg$)
作品。
obj.func
没有obj
作为上下文,而obj.func()
有。
添加回答
举报
0/150
提交
取消