开发者

Global Variables in JavaScript?

I'm new to Javascript and the following code is confusing the hell out of me. By my understanding, you can assign values to global variables by dropping the var in front of them, and you don't need to define any initial value when you declare the global in the first place. However, why is the following co开发者_StackOverflowde not working? (By not working I mean that the call to document.write within main() spits out "undefined" for "ulat").

var ulat;

function write(latitude) {
    ulat = latitude;
    document.write("<h1> This works:" + ulat + "</h1>");
}

function getloc() {

            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(
                function(position) {
                    write(position.coords.latitude);
                },
                function (error) {
                    switch(error.code) {
                        case error.TIMEOUT:
                            alert ('Timeout');
                            break;
                        case error.POSITION_UNAVAILABLE:
                            alert ('Position unavailable');
                            break;
                        case error.PERMISSION_DENIED:
                            alert ('Permission denied');
                            break;
                        case error.UNKNOWN_ERROR:
                            alert ('Unknown error');
                            break;
                    }
                });

            }
            else {
                alert("Geolocation is not supported by your web browser.");                 
            }       
}


function main() {
      getloc();
      document.write("<h1> This doesn't work: " + ulat + "</h1>");
}

Any help? Thanks!


getCurrentPosition is asynchronous. It doesn't run when you call it, it starts running when you call it. So when main checks for a value, the success callback hasn't been called, and nothing has been assigned to ulat.

So here's what your code does:

  1. main gets called
  2. main calls getloc
  3. getloc sees that geolocation is available and starts a geolocation request. Then it returns immediately.
  4. main outputs the value of ulat, which is still undefined.
  5. Some time later, your success callback (or, of course, failure) gets called. At that point, I'm a bit surprised that your page doesn't go blank, because you'll be calling document.write after the main parse, which implies a document.open, which tears down the page and starts with a blank slate. But I don't use document.write often enough to remember all the vagaries...


You need to call main: 'main();'


var is for local variables. For global variables give the reference alone or as window.reference. Try modifying your code to remove the first line var ulat;.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜