代码之家  ›  专栏  ›  技术社区  ›  timothyjoseph

为什么google变量从未声明时就存在?

  •  -1
  • timothyjoseph  · 技术社区  · 7 年前

    我在试用GoogleMapsapiforjavascript,并在HelloWorld部分找到了答案。

    <script>
      var map;
      function initMap() {
        map = new google.maps.Map(document.getElementById('map'), {
          center: {lat: -34.397, lng: 150.644},
          zoom: 8
        });
      }
    </script>
    
    <script src="https://maps.googleapis.com/maps/api/js?key=YOURAPIKEY&callback=initMap"
    async defer></script>
    

    我注意到了 map = new google.maps.Map() 使用变量google。如果我尝试只使用nodejs运行javascript代码,我会得到一个引用错误。

    var map;
    
    map = new google.maps.Map(document.getElementById('map'), {
      center: {lat: -34.397, lng: 150.644},
      zoom: 8
    });
    

    为什么没有 ReferenceError: google is not defined 使用浏览器在HTML中运行时发生?

    1 回复  |  直到 7 年前
        1
  •  0
  •   Sani Huttunen    7 年前

    因为它是在你引用的脚本中声明的 <script src="https://maps.googleapis... .

    引用脚本中的第一行:

    window.google = window.google || {};
    

    脚本的其余部分构建 google 对象:

    google.maps = google.maps || {};
    ...
    google.maps.Load = function(apiLoad) {
    

    等。

    推荐文章