javascript 变量在 angular.forEach 中不可访问
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15013016/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
variable is not accessible in angular.forEach
提问by Vural
I have a service
我有服务
app.service('myService', function() {
this.list = [];
this.execute = function() {
//this.list is reachable here
angular.forEach(AnArrayHere, function(val, key) {
//this.list is not reachable here
});
}
}
even in controller its accessible
即使在控制器中它也可以访问
function Ctrl($scope, myService) {
$scope.list = myService.list;
}
Can someone explain me why "this.list" is not reachable within the angular.foreach and how can I access to "this.list" ?
有人可以解释一下为什么在 angular.foreach 中无法访问“this.list”以及如何访问“this.list”?
回答by dnc253
The last parameter in the angular.forEach
(See http://docs.angularjs.org/api/angular.forEach) function is the context for this
. So you'll want something like this:
angular.forEach
(参见http://docs.angularjs.org/api/angular.forEach)函数中的最后一个参数是this
. 所以你会想要这样的东西:
app.service('myService', function() {
this.list = [];
this.execute = function() {
//this.list is reachable here
angular.forEach(AnArrayHere, function(val, key) {
//access this.list
}, this);
}
}
回答by Coin_op
The reason this.list
is not accessible in the foreach is because the context for that function call has changed. It works inside the execute
method as that method is part of the same context as list.
this.list
在 foreach 中无法访问的原因是该函数调用的上下文已更改。它在execute
方法内部工作,因为该方法与列表属于同一上下文。
Due to all the closures I would assign the this
context to another variable that you can then call later on. Something like this:
由于所有的闭包,我会将this
上下文分配给另一个变量,然后您可以稍后调用。像这样的东西:
app.service('myService', function() {
var self = this;
self.list = [];
self.execute = function() {
//this.list and self.list are reachable here
angular.forEach(AnArrayHere, function(val, key) {
//self.this == this.list
});
}
}
This is a slightly more general solution than passing the context as part of the foreach method call and would work in other closure related situations.
这是一个比作为 foreach 方法调用的一部分传递上下文更通用的解决方案,并且可以在其他与闭包相关的情况下工作。