为何不能直接将observer.next回调引用传入setTimeout?
为什么不能直接把 observer.next 的引用传入 setTimeout?
我想要打印 hello world,但下面这段代码会报错 this._next is not a function:
const obs = new Observable( (observer)=>{ setTimeout(observer.next, 0) } ); obs.subscribe(()=>{console.log("world")}); console.log("hello ");
改成以下形式就能正常运行:
const obs = new Observable( (observer)=>{ setTimeout(()=>{observer.next()}, 0) } ); obs.subscribe(()=>{console.log("world")}); console.log("hello ");
原因解析
- 核心问题是函数的
this绑定丢失:observer.next是依附于observer对象的方法,它内部的this原本指向observer。当你直接把observer.next单独作为参数传给setTimeout时,这个方法会脱离原对象的上下文——非严格模式下this会指向全局对象(浏览器环境为window),严格模式下this是undefined。而next方法内部需要通过this._next触发订阅的回调,此时this指向错误,自然会抛出this._next is not a function的报错。 - 用箭头函数
()=>{observer.next()}包裹后,箭头函数不会创建自己的this上下文,它会继承外层作用域的this,也就是当前的observer对象。调用observer.next()时,next方法的this能正确指向observer,可以正常访问this._next,代码也就正常执行了。
内容的提问来源于stack exchange,提问作者Urooj
相关产品推荐
相关产品推荐

