Google Maps API 3 - JavaScript 中的闭包
google maps api 3 - closure in 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 found");
正在工作请帮忙
在 else 块或"click"处理程序中无法访问它吗?如果您不能仅在"单击"处理程序中获取 array/thisCount,您是否尝试过复制这些变量?这可能是上下文的问题吗?试试这个,如果你的数组在 else 块中可见:
function makeTheFunction(array, thisCount) {
return function (point) {
if (!point) {
alert(array[thisCount] + " not found");
}
else {
var item = array[thisCount];
var marker = new GMarker(point);
map.addOverlay(marker);
GEvent.addListener(marker, "click", function () {
marker.openInfoWindowHtml(item + "</b>");
});
}
};
}
function makeTheFunction(array, thisCount)
{
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>");
});
}
return point;
}
我建议addListener
函数中出现问题。在提供的代码中,侦听器中的thisCount
应该在makeTheFunction
函数中对 thisCount 有一个闭包。
下面模拟发布的代码:
<script type="text/javascript">
function init() {
var count = 'the count';
partTwo(makeFn(count));
function makeFn(thisCount) {
return function() {
// Shows 'thisCount: the count'
alert('thisCount: ' + thisCount);
document.getElementById('btn0').addEventListener('click',
function(){alert('thisCount: ' + thisCount);}, false);
}
}
}
function partTwo(fn) {
fn();
}
window.onload = function() {
init();
};
</script>
<!-- Shows 'thisCount: the count' -->
<button id="btn0">Button 0</button>
但是,它使用浏览器addEventListener
附加侦听器,而不是明显的自定义addListener
。
相关文章:
- for循环中的JavaScript闭包
- Javascript闭包-如何防止内存泄漏
- Javascript.闭包和dynamic'这'实际上具有约束力
- 如何告诉闭包javascript编译器不要混淆webkitAudioContext的方法名称
- 如何使用外部Javascript库(如jQuery)重命名Google闭包样式表
- 就良好实践而言,带闭包的javascript原型是一件好事吗
- 闭包中的Javascript值
- 用于添加两个数字的javascript闭包的用法
- 什么'这个javascript闭包的区别是什么
- javascript,将参数传递给函数内部的闭包中的回调
- javascript中的闭包对我来说工作方式不同
- 我可以使用JavaScript闭包添加数字吗
- 在Javascript中使用闭包
- 这是在JavaScript中形成闭包的正确方法吗
- 作用域问题-此函数是否形成闭包-JavaScript
- JavaScript - 为什么这个闭包不保存参数
- javascript闭包:保护内部变量
- 如何测试只在闭包范围中可见的javascript方法
- JavaScript闭包&回调函数
- 闭包 JavaScript 有助于理解示例