【问题标题】:Very strange Javascript scoping issue非常奇怪的Javascript范围问题
【发布时间】:2012-06-17 15:34:28
【问题描述】:

以下变量 my_cords 在进入谷歌地图功能时未定义,任何人都可以理解为什么并可能给我一个解决方法吗?我已经在顶部定义了它并将它设置在一个回调函数中,我之前已经看到它在全局变量上工作..

$(document).ready(function () {

var my_cords;
var map;

function getCareHome() {

    geocoder = new google.maps.Geocoder();

    //var address = document.getElementById("address").value;

    var address = "address here";

    geocoder.geocode( { 'address': address}, function(results, status) {

        if (status == google.maps.GeocoderStatus.OK) {

            my_cords = results[0].geometry.location;

        } else {

            alert("Sorry we couldn't locate the carehome on the map: " + status);
            return false;

        }

    });



    var myOptions = {
        zoom: 7,
        center: my_cords,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }

    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

}

getCareHome();

});

【问题讨论】:

    标签: javascript variables scope


    【解决方案1】:

    geocoder.geocode 是一个异步函数。设置 my_cords 的匿名函数在某些事件(可能是 HTTP 响应的到达)触发之前不会运行。

    将依赖于它运行的代码移动到该函数内部。

    【讨论】:

    • 干杯,刚刚到帖子,不过我提高了你的答案!
    【解决方案2】:

    .geocode 是一个异步调用。

    尝试在函数中使用回调。

    例如:

    geocoder.geocode( { 'address': address}, function(results, status) {
    
        if (status == google.maps.GeocoderStatus.OK) {
    
            createMap(results[0].geometry.location);
    
        } else {
    
            alert("Sorry we couldn't locate the carehome on the map: " + status);
            return false;
    
        }
    
    });
    
    var createMap = function(my_cords)  {
         var myOptions = {
            zoom: 7,
            center: my_cords,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        }
    
        map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    }
    

    【讨论】:

    • 不建议使用var createMap = function... 表单。除此之外,+1。
    • @Neal:function createMap 我会使用函数声明,就像 OP 对 getCareHome 所做的那样,而不是函数表达式。
    • @T.J.Crowder 为什么我的方式有什么不同?我只是展示了我是如何创建函数的。我没有注意 OPs 的函数声明。
    • @Neal:它发生在不同的时间,并导致引用匿名函数的变量。函数声明发生在作用域中执行任何逐步代码之前,并导致绑定具有正确名称的函数。更多:Anonymouses anonymous
    • @Neal 你让它听起来很容易!感谢您的疯狂快速响应。学到了一些新东西。
    【解决方案3】:

    因为geocode 运行异步,你的代码使用my_cords 稍后(设置myOptions)将看到my_cords 的值之前完成回调从geocode 运行——所以myOptions.center 将是undefined

    如果您在设置myOptions 时需要my_cords,则必须将该代码移入geocode 上的回调。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-26
      • 1970-01-01
      • 2011-07-12
      • 2013-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多