This code from Google Maps文档页面对我来说是一个谜。代码片段中的功能指的是一个对象google
,一切都很好。Javascript对象只在函数内部可用,尽管没有被声明或传递给它们
我期望那个对象google
存在于全局范围内,因为它被全局函数使用,否则它们无法知道它(即它们没有声明它,并且它没有被传入作为参数)
例如,如果我看到这样
function() {
// do some calc
anotherFunction(resultOfCalc)
...
}
代码,我会认为anotherFunction
可至少在父范围 - 如果不是全球性的。
Here is the JSFiddle for the Google code。请注意,我添加了一行console.log("Google obj:", google);
在控制台正在打印
VM573:66 Uncaught ReferenceError: google is not defined
at VM573:66
但是,为什么?在代码的下一行是
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: {lat: -33.9, lng: 151.2}
});
setMarkers(map);
}
并没有有关使用google
compaint。
请帮我理解这种奇特的行为。
<script async defer src="https://maps.googleapis.com/maps/api/js?key=…&callback=initMap">
</script>
_Here是的jsfiddle ..._在哪里[** JSFiddle **](https://jsfiddle.net/)? –
有没有一些异步的东西在那里?也许这个“谷歌”对象异步加载,并且在加载之前使用它? –
@ibrahimmahrir在发布后加了一会 - 最初忘了。对不起 – CodyBugstein