JavaScript 中的闭包
function initialize(final)
{
if (GBrowserIsCompatible()) {
................................................
}
var address_array = final.split('~');
for (var count = 0; count < address_array.length; count++) {
if (geocoder) {
geocoder.getLatLng(
address_array[count],
makeTheFunction(address_array, count)
);
}
}
}
function makeTheFunction(array, thisCount) {
return function (point) {
if (!point) {
alert(array[thisCount] + " not found");
}
else {
var marker = new GMarker(point);
map.addOverlay(marker);
GEvent.addListener(marker, "click", function () {
marker.openInfoWindowHtml(array[thisCount] + "</b>");
});
}
};
}
我的问题是,我无法从 else 部分访问 array[thisCount],尽管可以从 if 块访问它。即 alert(array[thisCount] + " not find") ;
正在工作 请帮忙
function initialize(final)
{
if (GBrowserIsCompatible()) {
................................................
}
var address_array = final.split('~');
for (var count = 0; count < address_array.length; count++) {
if (geocoder) {
geocoder.getLatLng(
address_array[count],
makeTheFunction(address_array, count)
);
}
}
}
function makeTheFunction(array, thisCount) {
return function (point) {
if (!point) {
alert(array[thisCount] + " not found");
}
else {
var marker = new GMarker(point);
map.addOverlay(marker);
GEvent.addListener(marker, "click", function () {
marker.openInfoWindowHtml(array[thisCount] + "</b>");
});
}
};
}
my problem is tht i m not able to access the array[thisCount]
from the else section although its accessible from the if block.. i.e alert(array[thisCount] + " not found");
is working
please help
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 else 块或“click”处理程序中是否无法访问它?如果您无法仅在“单击”处理程序中获取 array/thisCount,您是否尝试过复制这些变量?这可能是上下文的问题吗?如果您的数组在 else 块中可见,请尝试此操作:
}
Is it inaccessible within else block or within “click” handler? If you cannot get array/thisCount only within your “click” handler, have you tried to copy these variables? Can it be an issue with contexts? Try this, if your array is visible within else block:
}
我建议
addListener
函数出了问题。在提供的代码中,侦听器中的thisCount
应该有一个对makeTheFunction
函数中的 thisCount 的闭包。以下模拟发布的代码:
但是,它使用浏览器
addEventListener
附加侦听器,而不是明显自定义的addListener
。I suggest that there is something going wrong in the
addListener
function. In the code provided,thisCount
in the listener should have a closure to thisCount in themakeTheFunction
function.The following emulates the posted code:
However it attaches the listener using the browsers
addEventListener
, not the apparently customaddListener
.