Rx-subscribe方法如何在不传递上下文的情况下保留上下文

How does Rx subscribe method preserve context without passing it

本文关键字:上下文 情况下 保留 方法 Rx-subscribe      更新时间:2023-09-26

我将Rx与Angular2一起使用,并使用Subscribe方法,方法的回调保留调用它的组件(或类)的上下文,而不传递任何引用。我的问题是他们如何做到这一点?Javascript的诀窍是什么?

代码片段:

this._userService.SignUpUser(this.model).subscribe(
     user => {
       this.newuser = user; // this, is actually same as the calling "this"? How does this work?      
       },
       error => this.errorMessage = <any>error  
);   

这是因为使用了一个提供词法this关键字的箭头函数。在这种情况下,this不是对应于执行函数的实例,而是对应于定义函数的实例。

它与Rx完全无关。

有关更多详细信息,请参阅此链接:

  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

这是因为=>而不是function()

https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Functions/Arrow_functions