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
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
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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.