我尝试通过以下示例来理解打字稿的箭头函数角2可观察的订阅方法。有人能给我解释一下吗:
我有这个有效的代码:
this.readdataservice.getPost().subscribe(
posts => { this.posts = posts; }
);
但如果我用这个应该是一样的吗?但这行不通。
this.readdataservice.getPost().subscribe(
function (posts) {
this.posts = posts;
}
);
箭头函数是匿名的,不绑定自己的this
。因此,this
is this
当前上下文。
正常功能绑定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)
);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)