FatalKeystroke FatalKeystroke - 2 months ago 8x
Javascript Question

Javascript object properties null outside of member functions

I have a site I'm making with Google Maps integration. Below is some sample code showing layout and where I'm having issues, I think it's scope related but can't figure it out. the Maps API calls initMap() once it's loaded to anything using the API has to be performed within initMap, but I also need obj to be a global variable so it can be accessed and do things after initMap() has finished.

var obj = {};
var initMap = function() {
obj = {
"map": null,
"locations": null,
"refreshStuff": function() {
// Do things to populate all the null values
// i.e.
obj.locations = [0,1,2,3,4,5];
alert(/*message to show values are what they should be*/); // They are
"otherThings": "otherThings"
alert(/*message to check values are still what they should be*/); // They're null
alert(/*message to check values are still what they should be*/); // They're null

Is there a reason that obj's null properties are reverting back to null once outside of the function that sets them?


The member vairables aren't always reverting to null, they're reverting to whatever they're se to initially, I just am using null initially for all of them.

obj = {
"location_ex1": null,
"location_ex2": 0
alert(obj.location_ex1); // null
alert(obj.location_ex1); // 0


Here is a full code snippet for one function that's not setting values correctly

obj = {
// ...
"userLocationFirstRun": true,
"refreshUserLocation": function() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
obj.userLocation.position = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
if (obj.userLocationFirstRun) {
obj.userLocationFirstRun = false;
obj.userLocation.marker = new google.maps.Marker({
map: obj.map,
position: obj.userLocation.position,
draggable: false,
icon: { url: "/images/location_marker.png" }
alert(JSON.stringify(obj.userLocation.position)); // <-- Correct coords
}, function() {
//Geolocation error - Service failed
alert("Geolocation service failed");
else {
//Geolocation error - No geolocation ability
alert("Geolocation service not available");
"userLocation": {
"marker": null,
"position": null,
// ...
alert(JSON.stringify(obj.userLocation.position)); // <-- null


I believe that when you use obj inside of refreshStuff, its obj which is equal to {}, before obj is updated to have the refresh stuff function, if yous eee what I mean.

In fact I am right, proof: