Reputation: 3489
I have a script section in my html file where I create a new instance of my gmap
object. Outside of the function initMap()
the variable gMap
is undefined although I declared it outside of the function.
var gMap;
function initMap() {
gMap = new gmap({
//some Properties
});
console.log(gMap); //gMap is defined
}
console.log(gMap); //gMap is undefined
The function is called like this:
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>
I also tried calling it through $(document).ready
instead of google API callback but it changed nothing.
Upvotes: 0
Views: 6409
Reputation: 4024
You get undefined because gMap
exist but it doesn't assign with any value when you call it with console.log
for the first time, outside of the function. Up until you call initMap()
- only then gMap
will get assigned with a value (or properties in your case). If you Don't want to get undefined before you call your function, you'll need to assign it some value on the 'outside function' scope,
Such as this simple example:
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);
Will produce the following output:
"im not undefined" //outside call
"im still not undefined" //inside function call
"im still not undefined" //second outside call
Upvotes: 2
Reputation: 31
I think you will find that's it's because you have not called the function. You need to call the function before logging it to have the value assigned.
EG:
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
Hope that helps!
Upvotes: 3
Reputation: 10703
You are correct, the google call back is running after your console.log().
So what is happening is
gMap
var. InitMap
functiongmap
gmap
outside of your function it is undefinedif you do this
$(document).ready(function(){
var gMap;
function initMap() {
gMap = new gmap({
//some Properties
});
console.log(gMap); //gMap is defined
}
console.log(gMap); //gMap is undefined
}
You will still get an undefined, because nothing is calling initMap
before you are logging gmap
. You need to gMap
to something before you try and log it
The below code will load gMap properly, without knowing what you are using it for its hard for me to give you working code to do what you need.
$(document).ready(function(){
var gMap = new gmap({});
console.log(gMap); //gMap is defined
}
Upvotes: 0