简体   繁体   English

Angular2订阅了解箭头功能

[英]Angular2 subscribe understand arrow function

I try to understand arrow functions of typescript by the example of Angular 2 Observable subscribe method. 我尝试通过Angular 2 Observable subscribe方法的例子来理解typescript的箭头函数。 Could somebody explain me: 有人可以解释我:

I have this code which works: 我有这个代码有效:

 this.readdataservice.getPost().subscribe(
            posts => { this.posts = posts; }
        );

but should it be the same if I use this? 但如果我使用它,它应该是一样的吗? But this doesn't work. 但这不起作用。

this.readdataservice.getPost().subscribe(
            function (posts) {
                this.posts = posts;
            }

        );
  1. Arrow function is anonymous and doesn't bind its own this . Arrow功能是匿名的,不会绑定自己的this Hence, this is this of current context. 因此, thisthis当前上下文的。

  2. Normal function binds this to the caller if we don't bind it explicitly 如果我们不明确地绑定它,则普通函数this绑定到调用者


Then 然后

    this.readdataservice.getPost().subscribe(
        posts => { this.posts = posts; }
    );

Can be

    var self = this;
    this.readdataservice.getPost().subscribe(
        function(posts) { self.posts = posts; }
    );

Or 要么

    this.readdataservice.getPost().subscribe(
        function(posts) { this.posts = posts; }.bind(this)
    );

JS by default executes functions in the scope of the caller. 默认情况下,JS执行调用者范围内的函数。 If you pass a function around to be called somewhere else, this points to the caller. 如果你传递一个函数来在其他地方调用, this指向调用者。 In your code you pass the function to the observable via the subscribe(...) method and then the function is called by the observable when an event is to be emitted. 在您的代码中,您通过subscribe(...)方法将函数传递给observable,然后在发出事件时由observable调用该函数。

If you use arrow function, then this keeps pointing to the class where it is defined. 如果您使用箭头功能,那么this不断指着它被定义的类。

An alternative is using .bind(this) to tell JS this should keep pointing at the current class instance. 另一种方法是使用.bind(this)来告诉JS this应该继续指向当前的类实例。

    this.readdataservice.getPost().subscribe(
        function (posts) {
            this.posts = posts;
        }.bind(this)

    );

See also https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Functions/Arrow_functions 另请参见https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Functions/Arrow_functions

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM