循环内回调的Javascript闭包访问

时间:2015-05-10 12:58:01

标签: javascript angularjs scope

如何让最后一行代码返回一个值?

$scope.runActionwithObjects = function() {

            for (var i = 0; i < $scope.Objects.length; i++) {
                console.log($scope.Objects[i]); //$scope is accessible
                $http.get($scope.Objects[i]["Commit"]).success(function (data) {
                    console.log($scope.Objects[i]);//return undefined

2 个答案:

答案 0 :(得分:1)

您的$scope.Objects[i]未定义的原因是因为变量i总是= $scope.Objects.lenth + 1,例如您有5个元素,i将是6,因为回调时,它已经有了最后一个价值。

一种解决方案是将所需对象绑定到该方法,因此我们可以通过this访问它(我们无法通过闭包直接引用ref变量,因为它仍然存储了最后一项),例如:

           for (var i = 0; i < $scope.Objects.length; i++) {
               var ref = $scope.Objects[i];
               // console.log($scope.Objects[i]); //$scope is accessible
               var successCallback = (function (data) {
                   console.log(this);//return the ref

               }).bind(ref);
               $http.get('').success(successCallback);
           }
       }

答案 1 :(得分:1)

问题是由于ajax请求的异步

执行success回调后,您的循环已完成i变量已等于$scope.Objects.length

试试forEach。此函数将为数组中的项创建不同的闭包。

$scope.Objects.forEach(function(currentObject){
    console.log(currentObject); //$scope is accessible
    $http.get(currentObject["Commit"]).success(function (data) {
        console.log(currentObject);
    });
});