Javascript-事件处理程序中的变量范围 [英] Javascript - variable scope in event handler

查看:62
本文介绍了Javascript-事件处理程序中的变量范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以阐明我对事件处理程序中变量范围的理解吗?看看下面的代码:

Can someone clarify the my understanding of variable scope within event handlers? Take a look at the code below:

var address = new Array();
address[0] = '1 Smith Street';
address[1] = '2 Smith Street';

for(var rownum=0; rownum<=address.length; rownum++)
{
        if(address[rownum])
                geocoder.geocode( {'address': address[rownum]}, geocodeCallBack);
}


function geocodeCallBack(results, status)
{
        var marker = new google.maps.Marker({
            map: map,
            position: results[0].geometry.location,
            title: results[0].formatted_address
        });

        google.maps.event.addListener(marker, 'click', function(){
                var infowindow = new google.maps.InfoWindow({
                content: marker.title
                });
                // how come this event handler knows the marker variable references the marker variable declared about 10 lines above?
                infowindow.open(map, marker);
        });
}

对于大多数人来说,这段代码看起来很简单.它在Google地图上绘制了两个标记.当您单击第一个标记时,它将显示地址"1 Smith Street".当您单击第二个标记时,它将显示地址"2 Smith Street".

For most people, this code seems straight-forward. It plots two markers on google maps. When you click on the first marker, it shows the address '1 Smith Street'. When you click on the second marker, it shows the address '2 Smith Street'.

好吧,我的问题是:两个标记为何都不显示史密斯街2号" ?

Ok so my question is: how come BOTH markers don't show '2 Smith Street'?

过去,我遍历对象数组并将事件处理程序绑定到每个对象.在事件处理程序代码本身中,我将尝试重新引用数组中的相应对象,该对象不在事件处理程序的范围之内.因此,在页面加载结束时,所有对象的事件处理程序都在循环中引用了LAST元素.上面的示例地理编码为何没有遇到相同的问题?

In the past, I've looped through arrays of objects and bound event handlers to each object. In the event handler code itself, I would try to re-reference the corresponding object in the array, which is outside of the scope of the event handler. Thus, at the end of page load, the event handler for ALL objects referenced the LAST element in the loop. How come my sample geocode above didn't experience the same problem?

如果我不能很好地阐明问题,请原谅我.这是因为对情况非常困惑.我似乎无法用事件处理程序来处理可变范围.....如果有人可以帮助我澄清一下,那就太好了.

Forgive me if I'm not articulating the problem well. It is because very confused about the situation. I can't seem to get my head wrapped around variable scope with event handlers.....if someone can help me clarify, that would be great.

其他信息/困惑 另一件事...变量var markergeocodeCallBack()的范围内被实例化.用户在运行时触发google.maps.event.addListener(marker, 'click', function(){})时标记是否已被破坏?在那种情况下,我应该得到某种不确定的错误?

Additional Info/Confusion Another thing...the variable var marker was instantiated in the scope of geocodeCallBack(). Isn't the marker destroyed by the time a user triggers google.maps.event.addListener(marker, 'click', function(){}) during run time? In which case, I should get some kind of undefined error?

推荐答案

{'address': address[rownum]}是对象文字.因此,其值是在执行该语句所包含的语句的确切时间确定的,将来对addressrownum所做的更改将不会影响该对象的address成员.

{'address': address[rownum]} is an object literal. Therefore, its value is determined at the exact time that the statement it is part of is executed, and future changes to address or rownum will not affects the object's address member.

您可能已经习惯了使用闭包(从父作用域引用变量的函数)来解决此问题.这完全是一个不同的问题,因为该函数的主体通常要到一段时间后才执行.这样的函数继续引用相同的变量,而不仅仅是引用相同的值.

You are probably used to seeing this problem with closures (functions that reference variables from a parent scope). That is a different problem entirely, since the body of the function is usually not executed until some time later. Such a function continues to reference the same variables, not simply the same values.

但是在这种情况下,您根本不会在for循环中创建任何函数.

But in this case, you are not creating any functions at all in your for loop.

否,marker变量仍然有效-这是闭包操作的一部分.如果您是C语言背景,这的确看起来很神秘.外部函数已返回;它的当地人怎么会继续存在!?

No, the marker variable will still be alive -- that's part of what closures do. If you're from a C background, this will indeed seem mysterious. The outer function has returned; how could its locals continue to exist!?

答案是这些变量被匿名函数关闭",运行时将保留它们的存在,直到不再引用匿名函数为止.

The answer is that these variables get "closed around" by the anonymous function, and the runtime preserves their existence until the anonymous function is no longer referenced.

这篇关于Javascript-事件处理程序中的变量范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆