我在我的服务中使用了一个函数,定义为:
var getData = function() {
return anotherService.getData().$promise;
};
Run Code Online (Sandbox Code Playgroud)
以及this我在整个服务中操纵的属性.
this.someProperty = 'a string';
Run Code Online (Sandbox Code Playgroud)
我在我的服务的返回部分调用上面的函数:
return{
updateProperty: function(){
getData().then(function(data){
this.someProperty = data;
});
}
}
Run Code Online (Sandbox Code Playgroud)
在上面,我this is undefined在浏览器控制台中收到相关错误.我假设这是因为已解析$promise是一个AJAX调用,并且this在上下文之外使用.this在此实例中,使用来自AJAX调用的返回数据操作属性的最佳方法是什么?
Ben*_*esh 13
如果您在this整个服务中进行操作,请将其分配给变量var self = this.问题是这this是函数的上下文,可以使用fn.call(context)或更改其他代码fn.apply(context, args).因此,在任何给定函数的范围内,它可能会有所不同.
所以只需将它分配给某个变量并使用它:
var self = this;
return {
updateProperty: function(){
getData().then(function(data){
self.someProperty = data;
});
}
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1808 次 |
| 最近记录: |