将带有 javascript 闭包的参数附加到匿名函数中的默认参数
我想向 Google geocoder API 调用添加一些额外的参数,因为我在循环中运行它,但不确定如何将闭包参数附加到其匿名函数,该函数已经具有通过调用传入的默认参数API。
例如:
for(var i = 0; i < 5; i++) {
geocoder.geocode({'address': address}, function(results, status) {
// Geocoder stuff here
});
}
我希望能够在传递的 geocoder.geocode() 匿名函数中使用 i 的值,但是如果我在第 4 行使用 }(i));
进行闭包这将替换第一个会破坏地理编码器的参数。
有没有办法可以使用闭包,或者将 i 的值传递到匿名函数中?
实际上我想做的是:
geocoder.geocode({'address': address}, function(results, status, i) {
alert(i); // 0, 1, 2, 3, 4
}(i));
但是工作:-)
I want to add some extra parameters to the Google geocoder API call as I'm running it in a loop, but am not sure how to append closure parameters to their anonymous function that already has default parameters that are passed in by the call to the API.
For example:
for(var i = 0; i < 5; i++) {
geocoder.geocode({'address': address}, function(results, status) {
// Geocoder stuff here
});
}
I want to be able to use the value of i in the passed geocoder.geocode() anonymous function, but if I had a closure using }(i));
on line 4 for example that would replace the first parameter which would break the geocoder.
Is there a way I can use closures, or pass the value of i into the anonymous function at all?
Effectively what I want to do is:
geocoder.geocode({'address': address}, function(results, status, i) {
alert(i); // 0, 1, 2, 3, 4
}(i));
but working :-)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以直接从匿名函数(通过闭包)访问
i
,但您需要捕获它,以便每次调用geocode
都能获得自己的副本。与 JavaScript 中通常的做法一样,添加另一个函数就可以解决问题。我重命名了外部i
变量以使其更清晰:You can access
i
directly from you anonymous function (via closure), but you need to capture it so that each call togeocode
gets its own copy. As usual in javascript, adding another function will do the trick. I renamed the outeri
variable to make it clearer:应该做...
Oughta do it...