2010-10-20 56 views
5

我想在Google地理編碼器API調用中添加一些額外的參數,因爲我在循環中運行它,但不確定如何將閉包參數附加到它們的匿名函數已經具有通過調用API傳入的默認參數。將JavaScript關閉參數附加到匿名函數中的默認參數

例如:

for(var i = 0; i < 5; i++) { 
    geocoder.geocode({'address': address}, function(results, status) { 
     // Geocoder stuff here 
    }); 
} 

我希望能夠用我的價值傳遞geocoder.geocode()匿名函數,但如果我在第4行使用}(i));例如閉包將取代會破壞地理編碼器的第一個參數。

有沒有一種方法可以使用閉包,或將我的值傳遞給匿名函數?

有效是我想要做的是:

geocoder.geocode({'address': address}, function(results, status, i) { 
    alert(i); // 0, 1, 2, 3, 4 
}(i)); 

但:-)工作

回答

11

您可以從您的匿名函數直接訪問i (通過關閉),但您需要捕獲它,以便每次撥打geocode時都會獲得自己的副本。像往常一樣,在JavaScript中,添加另一個函數將做到這一點。我將外部變量i改名爲更清楚:

for(var iter = 0; iter < 5; iter++) { 
    (function(i) { 
     geocoder.geocode({'address': address}, function(results, status) { 
      // Geocoder stuff here 
      // you can freely access i here 
     }); 
    })(iter); 
} 
+0

更簡單的解決方案!應該早些發佈吧 – WheresWardy 2010-10-20 14:31:58

+1

我想說的是,在外部範圍和內部範圍內有'i',我感到困惑,但是我看到你現在已經修復了這個問題,所以我會讓你離開:) – Skilldrick 2010-10-20 14:35:06

+0

我建議這個例子是最好的,因爲其他人(他們更簡單)在我的情況下不起作用:geocoder回調函數中的i始終是循環中的最後一個。我想,這取決於瀏覽器的異步性質。 但這個答案完美工作! +1! – Igor 2014-04-18 18:42:25

3
function geoOuter(i) { 
    geocoder.geocode({'address': address}, function(results, status) { 
     // Geocoder stuff here 
     // This has access to i in the outer function, which will be bound to 
     // a different value of i for each iteration of the loop 
    }); 
} 

for(var i = 0; i < 5; i++) { 
    geoOuter(i); 
} 

現在應該做...

+0

這樣一個簡單的答案。非常感謝:-) – WheresWardy 2010-10-20 14:29:25