[英]How can I access variables in a closure from inside of a function in that closure?
[英]callback function access to closure variables?
下面這段代碼有一個bug,但它開了一個有趣的問題。 它使用angular的$ http服務返回一個promise。 解析后,回調函數無權訪問s1變量。
var ids = [];
ids = ['81074'];
// show what's in
for (var s=0;s<ids.length;s++) {
var s1 = s;
$http.get('http://mydomain.com/api/catalog/product/' + ids[s]).
success(function(data) {
// console.log(s1); <--- reference error
$scope.products[s].setProductData(data);
}).error(function(err){
console.log('--------- error',err);
});
};
s1給出ReferenceError:調試器中未定義s1
有趣的是,它確實可以訪問for循環變量s,它始終為1 - 正如預期的那樣,因為promise在增加后得到解決(因此錯誤BTW)
有人能解釋為什么嗎?
謝謝
利奧爾
這是for
循環中異步回調的經典問題。 s
和s1
都只聲明一次。 即使你聲明var s1;
在循環中,JavaScript沒有塊范圍,所以它是無關緊要的。
這意味着所有迭代共享相同的變量s
和s1
,因此當回調完成時, $scope.products[s]
正在查找ids.length + 1
產品。
相反,做:
var ids = [];
ids = ['81074'];
function launchRequest(s) {
$http.get('http://example.com/api/catalog/product/' + ids[s]).success(function (data) {
$scope.products[s].setProductData(data);
}).error(function (err) {
console.log('--------- error', err);
});
}
// show what's in
for (var s = 0; s < ids.length; s++) {
launchRequest(s);
}
......這里面引入了新的功能級別范圍launchRequest
,這意味着s
仍然是s
函數內部時,回調解析。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.