简体   繁体   English

新手javascript范围问题

[英]newbie javascript scope problem

I know a bit about what scope is, i am new to javascript and have hit a full stop in my code. 我知道一些范围是什么,我是javascript的新手并且在我的代码中完全停止了。 Here is the code that i use. 这是我使用的代码。

function initialize() {
      var mapOptions = {
        center: new google.maps.LatLng(37.775057,-122.419624),
        zoom: 8,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      };
      var map = new google.maps.Map(document.getElementById("map-canvas"),
          mapOptions);
      }
google.maps.event.addDomListener(window, 'load', initialize);
function clicked(id) {
  $.ajax({
    type: "GET",
    url: 'response.php',
    data: {id: id},
    success: function (lats) {
      var obj = $.parseJSON(lats);
      var line = [];
      for (var i = obj.length - 1; i >= 0; i--) {
        line.push(new google.maps.LatLng(obj[i].latitude, obj[i].longitude));
      };
      var polyPath = new google.maps.Polyline({
    path: line,
    strokeColor: "#FF0000",
    strokeOpacity: 1.0,
    strokeWeight: 2
  });
      polyPath.setMap(map);
      console.log(polyPath);
    }
  });
  return false;
}

Needless to say its google maps. 不用说它的谷歌地图。 Problem is that due to scope, javascript cant access the map variable that is required to draw the polylines. 问题是由于范围,javascript无法访问绘制折线所需的地图变量。 Help is highly appreciated! 非常感谢帮助!

because map is declared inside the function initialize , clicked can't access it you need to declare it outside initialize like 因为map是在函数initialize声明的, clicked无法访问它你需要声明它在initialize之外

var map = null;
function initialize() {
      var mapOptions = {
        center: new google.maps.LatLng(37.775057,-122.419624),
        zoom: 8,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      };
      map = new google.maps.Map(document.getElementById("map-canvas"),
          mapOptions);
    }
google.maps.event.addDomListener(window, 'load', initialize);
function clicked(id) {
  $.ajax({
    type: "GET",
    url: 'response.php',
    data: {id: id},
    success: function (lats) {
      var obj = $.parseJSON(lats);
      var line = [];
      for (var i = obj.length - 1; i >= 0; i--) {
        line.push(new google.maps.LatLng(obj[i].latitude, obj[i].longitude));
      };
      var polyPath = new google.maps.Polyline({
    path: line,
    strokeColor: "#FF0000",
    strokeOpacity: 1.0,
    strokeWeight: 2
  });
      polyPath.setMap(map);
      console.log(polyPath);
    }
  });
  return false;
}

now clicked can access it because it's outside the initialize scope 现在clicked可以访问它,因为它在initialize范围之外

You can move map to the global scope. 您可以将map移动到全局范围。

var map;
function initialize() {
    ...
    map = ....;
}

If you're concerned with polluting the global scope, you can put both inside a single function to preserve the namespace: 如果您担心污染全局范围,可以将两者放在一个函数中以保留命名空间:

(function() {
     var map;
     function initialize() {
         ...
         map = ....;
     }
     ...(everything else) ...
})();

If you are referring to getting the map variable from your initialize function, here is what you would need to do. 如果您指的是从initialize函数中获取map变量,那么您需要执行此操作。

var map;
function initialize() {
    var mapOptions = {
        center: new google.maps.LatLng(37.775057,-122.419624),
        zoom: 8,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById("map-canvas"),
        mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
function clicked(id) {
    $.ajax({
        type: "GET",
        url: 'response.php',
        data: {id: id},
        success: function (lats) {
            var obj = $.parseJSON(lats);
            var line = [];
            for (var i = obj.length - 1; i >= 0; i--) {
                line.push(new google.maps.LatLng(obj[i].latitude, obj[i].longitude));
            };
            var polyPath = new google.maps.Polyline({
                path: line,
                strokeColor: "#FF0000",
                strokeOpacity: 1.0,
                strokeWeight: 2
            });
            polyPath.setMap(map);
            console.log(polyPath);
        }
    });
    return false;
}

What I have done is declare map outside the initialize function. 我所做的是在initialize函数之外声明map In this case, it will have global scope to all of your Javascript code that you can call later. 在这种情况下,它将具有您可以稍后调用的所有Javascript代码的全局范围。 The initialize function will be able to set it for you and the AJAX call will be able to read it. 初始化函数将能够为您设置它,AJAX调用将能够读取它。

An alternative to declaring map outside of the initialise function would be using window.map which assigns it as the map property on the window object. 在初始化函数之外声明map的替代方法是使用window.map ,它将其指定为window对象上的map属性。 As the window object can be accessed anywhere as it is global, you just need to call window.map to read and write to it anywhere. 由于窗口对象可以在任何地方访问,因为它是全局的,您只需要调用window.map来随处读取和写入它。

一个快速但不推荐的解决方案是删除map前面的var ,使其成为一个全局变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM