Angular2订阅了解箭头功能
Angular2 subscribe understand arrow function
我试图通过 Angular 2 Observable subscribe 方法的例子来理解 typescript 的箭头函数。有人可以解释一下吗:
我有这个有效的代码:
this.readdataservice.getPost().subscribe(
posts => { this.posts = posts; }
);
但是我用这个应该是一样的吧?但这是行不通的。
this.readdataservice.getPost().subscribe(
function (posts) {
this.posts = posts;
}
);
JS 默认在调用者的范围内执行函数。如果你传递一个函数在其他地方调用,this
指向调用者。
在您的代码中,您通过 subscribe(...)
方法将函数传递给可观察对象,然后在要发出事件时由可观察对象调用该函数。
如果使用箭头函数,那么 this
会一直指向定义它的 class。
另一种方法是使用 .bind(this)
告诉 JS this
应该继续指向当前的 class 实例。
this.readdataservice.getPost().subscribe(
function (posts) {
this.posts = posts;
}.bind(this)
);
另见 https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Functions/Arrow_functions
Arrow 函数是匿名的,不绑定它自己的 this
。因此,this
是当前上下文的 this
。
如果我们不显式绑定,普通函数会this
绑定到调用者
然后
this.readdataservice.getPost().subscribe(
posts => { this.posts = posts; }
);
可以
var self = this;
this.readdataservice.getPost().subscribe(
function(posts) { self.posts = posts; }
);
或
this.readdataservice.getPost().subscribe(
function(posts) { this.posts = posts; }.bind(this)
);
我试图通过 Angular 2 Observable subscribe 方法的例子来理解 typescript 的箭头函数。有人可以解释一下吗:
我有这个有效的代码:
this.readdataservice.getPost().subscribe(
posts => { this.posts = posts; }
);
但是我用这个应该是一样的吧?但这是行不通的。
this.readdataservice.getPost().subscribe(
function (posts) {
this.posts = posts;
}
);
JS 默认在调用者的范围内执行函数。如果你传递一个函数在其他地方调用,this
指向调用者。
在您的代码中,您通过 subscribe(...)
方法将函数传递给可观察对象,然后在要发出事件时由可观察对象调用该函数。
如果使用箭头函数,那么 this
会一直指向定义它的 class。
另一种方法是使用 .bind(this)
告诉 JS this
应该继续指向当前的 class 实例。
this.readdataservice.getPost().subscribe(
function (posts) {
this.posts = posts;
}.bind(this)
);
另见 https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Functions/Arrow_functions
Arrow 函数是匿名的,不绑定它自己的
this
。因此,this
是当前上下文的this
。如果我们不显式绑定,普通函数会
this
绑定到调用者
然后
this.readdataservice.getPost().subscribe(
posts => { this.posts = posts; }
);
可以
var self = this;
this.readdataservice.getPost().subscribe(
function(posts) { self.posts = posts; }
);
或
this.readdataservice.getPost().subscribe(
function(posts) { this.posts = posts; }.bind(this)
);