为何Google Maps API仅兼容var声明的initMap函数?
为什么用let/const声明initMap时Google Maps API报错,var却可以?
这个问题我之前也碰到过,核心原因是var、let/const在全局作用域下的挂载规则差异,咱们一步步拆解清楚:
1. 全局变量的挂载逻辑不同
- 当你用
var声明函数(或变量)时,这个标识符会自动挂载到全局对象上(浏览器环境里就是window对象)。Google Maps API的callback参数是在全局作用域中查找对应的函数,所以它能找到window.initMap,顺利执行回调。 - 而
let和const是ES6新增的块级作用域声明方式,它们不会把声明的标识符挂载到全局对象上。你的initMap函数只存在于当前<script>标签的块级作用域内,全局作用域根本访问不到它,API自然就抛出了InvalidValueError: initMap is not a function的错误。
2. 简单验证一下结论
你可以在浏览器控制台做个测试:
- 用
var声明initMap后,输入window.initMap,会返回你定义的函数; - 换成
let/const后,输入window.initMap,会返回undefined,说明全局对象上没有这个函数。
3. 除了换回var,还有这些解决方法
方法一:手动挂载到全局对象
把声明的函数主动挂载到window上,让API能在全局找到它:
const initMap = function () { // Create a map object and specify the DOM element for display. let map = new google.maps.Map(document.getElementById('map'), { center: {lat: -34.397, lng: 150.644}, zoom: 8 }); }; window.initMap = initMap; // 手动挂载到全局对象
方法二:使用函数声明而非函数表达式
函数声明会被提升到全局作用域,同样能被API识别:
function initMap() { // Create a map object and specify the DOM element for display. let map = new google.maps.Map(document.getElementById('map'), { center: {lat: -34.397, lng: 150.644}, zoom: 8 }); }
内容的提问来源于stack exchange,提问作者Sandeep Gupta
相关产品推荐
相关产品推荐

