繁体   English   中英

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

[英]Why does google variable exist when it has never been declared?

我正在试用 Google Maps API for Javascript,并遇到了 Hello World 部分。

<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 代码,我会得到一个 ReferenceError。

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 中运行时发生?

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

引用脚本中的第一行:

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

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

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

等等。

暂无
暂无

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

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