循环访问对象时访问 propertyname

Access propertyname while looping through an object

正如您在我在此问题中提供的代码中看到的那样,我尝试遍历对象的属性。所有属性都是空对象!我还有另一个对象,我在其中存储了几个 rest-calls(ngResource Stuff 对于这个问题并不重要)。

这里可以看到"Rest-Calls"存储在$scope.restCalls.

$scope.restCalls = [
   {
     resource1: RestService.call1,
     resource2: RestService.call2,
     resource3: RestService.call3
   },
   {
     resource4: RestService.call4,
     resource5: RestService.call5,
     resource6: RestService.call6
   },
   {
     resource7: RestService.call7,
     resource8: RestService.call8,
     resource9: RestService.call9
   }
];

$scope.data 符号化了每个 tab 的数据。该数组中的每个对象都保存选项卡的数据。所有资源初始化为空,如果用户更改页面,资源将存储在这里。

$scope.data = [
   {
     resource1: {},
     resource2: {},
     resource3: {}
   },
   {
     resource4: {},
     resource5: {},
     resource6: {}
   },
   {
     resource4: {},
     resource5: {},
     resource6: {}
   }
];

到目前为止一切顺利。我保证通话正常。在我的应用程序中有多个选项卡,所以我想尝试实现一些延迟加载:D

所以我实现了一个功能:(索引定义在html中,只是0到2之间的一个数)

<uib-tab heading="Tab1" select="tabChange(0)">
... HERE I have some tables which access the $scope.data[0] data
</uib-tab>
<uib-tab heading="Tab2" select="tabChange(1)">
... HERE I have some tables which access the $scope.data[1] data
</uib-tab>
<uib-tab heading="Tab3" select="tabChange(2)">
... HERE I have some tables which access the $scope.data[2] data
</uib-tab>

这里可以看到函数:

$scope.tabChange = function (index) {
        for (var propertyName in $scope.data[index]) {
            $scope.restCalls[index][propertyName]().$promise.then(function (data) {
                $scope.data[index][propertyName] = data;
            });
        }
    };

现在进入问题描述:

结果只存储到 $scope.data[index] 的错误 属性 中。它始终是最后一个 属性 名字。因此,例如我更改为 tab2(索引 1)。 $scope.data 会变成这样:

$scope.data = [
   {
     resource1: {},
     resource2: {},
     resource3: {}
   },
   {
     resource4: {},
     resource5: {},
     resource6: RESULT OBJECT OF THE LAST REST CALL!
   },
   {
     resource7: {},
     resource8: {},
     resource9: {}
   }
]; 

我认为 属性namethen 函数 中不可用。但我不知道如何将名称放入此函数中。

问题的出现是因为propertyName在函数的上层作用域中,在调用函数之前改变了它的值。您可以将变量绑定到函数范围,如下所示。

$scope.tabChange = function (index) {
        for (var propertyName in $scope.data[index]) {
            $scope.restCalls[index][propertyName]().$promise.then(function (propertyName,data) {
                $scope.data[index][propertyName] = data;
            }.bind(null,propertyName));
        }
    };

您可以了解有关 javascript 闭包的更多信息 here 以及您可以从 Google.

找到的其他来源