[英]A javascript variable defined outside a function is 'undefined' within the function
[英]JavaScript Variable undefined outside of function
我的html文件中有一个脚本部分,可在其中创建gmap
对象的新实例。 在函数initMap()
,变量gMap
未定义,尽管我在函数外部声明了它。
var gMap;
function initMap() {
gMap = new gmap({
//some Properties
});
console.log(gMap); //gMap is defined
}
console.log(gMap); //gMap is undefined
该函数的调用方式如下:
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>
我也尝试通过$(document).ready
而不是Google API回调来调用它,但是它什么都没有改变。
您会因为gMap
存在而未定义,但是在函数外部首次使用console.log
调用它时,它不会分配任何值。 直到调用initMap()
-才向gMap
分配一个值(或您的情况下的属性)。 如果您不希望在调用函数前得到不确定的定义,则需要在“外部函数”范围内为其分配一些值,
如这个简单的例子:
var gMap = 'im not undefined';
function initMap() {
gMap = 'im still not undefined';
console.log(gMap); //gMap is defined
}
console.log(gMap);
initMap();
console.log(gMap);
将产生以下输出:
"im not undefined" //outside call
"im still not undefined" //inside function call
"im still not undefined" //second outside call
我想您会发现这是因为您尚未调用该函数。 您需要先调用该函数,然后再记录该函数以分配值。
例如:
var gMap;
function initMap() {
gMap = new gmap({
//some Properties
});
console.log(gMap); //gMap is defined
}
console.log(gMap); //gMap is undefined
initMap();
console.log(gMap); //gMap is defined
希望有帮助!
您是正确的,在console.log()之后运行google回调。
所以发生的是
gMap
var。 InitMap
函数 gmap
gmap
,它是未定义的 如果你这样做
$(document).ready(function(){
var gMap;
function initMap() {
gMap = new gmap({
//some Properties
});
console.log(gMap); //gMap is defined
}
console.log(gMap); //gMap is undefined
}
您仍然会得到未定义的信息,因为在登录gmap
之前没有任何调用initMap
。 您需要先gMap
到某些内容,然后再尝试对其进行记录
下面的代码将正确加载gMap,而不知道您使用它的原因,这使我很难为您提供工作代码来执行所需的工作。
$(document).ready(function(){
var gMap = new gmap({});
console.log(gMap); //gMap is defined
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.