我想打印 hello world
const obs = new Observable( (observer)=>{ setTimeout(observer.next, 0) } );
obs.subscribe(()=>{console.log("world")});
console.log("hello ");
这会产生错误 this._next 不是函数
如果我写以下内容,效果很好:
const obs = new Observable( (observer)=>{ setTimeout(()=>{observer.next()}, 0) } );
obs.subscribe(()=>{console.log("world")});
console.log("hello ");
为什么我不能将observer.next回调的引用直接传递给setTimeout()?
在 RXJS 中,
.next()
函数的内部使用 this
。为了更好地理解,next
方法被定义为像这样:
next(value: T): void {
if (this.isStopped) {
handleStoppedNotification(nextNotification(value), this);
} else {
this._next(value!);
}
}
此方法内部
this
的值取决于它的调用方式(有关更多信息,请参阅 this)。当您使用以下方式调用它时:
observer.next()
正如您在第二个示例中所做的那样,
this
值被设置为您在其上调用observer
方法的next
对象,从而允许它在内部最终最终在._next()
上调用
observer
时正确运行对象。但是,当您在第一个示例中将
next
函数引用传递给 setTimeout()
时:
setTimeout(observer.next, 0)
您丢失了
this
上下文(即 observer
),因为现在您只是将 next
的函数引用传递给 setTimeout()
,而不再调用特定对象上的方法。当 setTimeout()
在指定的延迟后最终调用 next
函数时,它没有任何有关其调用的函数来自何处的信息,因此一旦调用默认值,this
方法内部的 next
值到全局对象,或者在严格模式下未定义,两者都没有_next()
方法。
.bind()
函数的可观察量,它返回一个新函数,其中 this
值显式设置为 observable
:
setTimeout(observer.next.bind(observer), 0)