Jump to content

Variable Scope


slarson8821

Recommended Posts

      function initialize() {

        function successCallback(pos){
	  LAT = pos.coords.latitude;
	  LON = pos.coords.longitude;
	  load();
        }

	function errorCallback(){
	  alert("FAIL");
	}

        if(navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(successCallback, errorCallback, {enableHighAccuracy: true});
        }else {
          alert('Sorry, your browser does not support geolocation.');
        }

      }

 

Makes the LAT and LON available outside the function, i thought since I didnt do var LAT = 0; and var LON = 0; outside of the function that it would be function access only.

Link to comment
https://forums.phpfreaks.com/topic/253277-variable-scope/
Share on other sites

You have to use the var keyword to limit the scope.  When you use a variable, JS will walk up the scope chain to find it.  If it gets up to the global scope before finding it, it will create it there.  Using the 'var' keyword will declare the variable at that scope level so JS will find it and not look further.

 

Though not really technically correct, you can think of it as:

Variables are global by default, and you use 'var' to make them local.

 

Link to comment
https://forums.phpfreaks.com/topic/253277-variable-scope/#findComment-1298692
Share on other sites

You have to use the var keyword to limit the scope.  When you use a variable, JS will walk up the scope chain to find it.  If it gets up to the global scope before finding it, it will create it there.  Using the 'var' keyword will declare the variable at that scope level so JS will find it and not look further.

 

Great summary.

Link to comment
https://forums.phpfreaks.com/topic/253277-variable-scope/#findComment-1298693
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.