开发者

Class and attribute problem

开发者 https://www.devze.com 2023-04-02 03:28 出处:网络
I wanted to play with geolocation API on my Android. I know that there is a \"navigator\" object that 开发者_如何学编程is defined and that should be used to aquire user position. So, I created this sa

I wanted to play with geolocation API on my Android. I know that there is a "navigator" object that 开发者_如何学编程is defined and that should be used to aquire user position. So, I created this sample code:

function GeolocationTester()
{
    // here I want to store all acquired locations
    this.locations = new Array();
    alert("this.locations defined: " + this.locations);
    this.onSuccess = function(position)
    {
        alert("Entered onSuccess");
        alert("this.locations defined: " + this.locations);
    }

    this.onError = function(error)
    {
        alert("error acquiring location");
    }
    navigator.geolocation.watchPosition(this.onSuccess, this.onError, { enableHighAccuracy: true });
}

And it doesn't work for me. Each time watchPosition call onSuccess the this.locations field isn't defined (and it is defined just after new Array). I known that I'm doing somethind wrong, but as it is one of my JavaScript attempts, not sure what. So, anybody could find a problem here?


The problem is with the scoping of this. When the onSuccess or onError is called, this isn't bound to the object containing the locations array. You need to create an explicit variable outside of the functions to which the array should be assigned and then use this variable in the callbacks, like this:

var allLocations = this.locations = [a, b, c];
this.onSuccess = function(position) {
    alert("allLocations: " + allLocations);
    alert("this.locations: " + this.locations);
}


Its cause you using this. This will change cause its depends on the context your function is calling on. Just use the scope of the function to declare location:

function GeolocationTester()
{
    // here I want to store all acquired locations
    var locations = [];
    alert("locations defined: " + locations);

    function onSuccess(position)    {
        alert("Entered onSuccess");
        alert("locations defined: " + locations);
    }

   function onError(error){
        alert("error acquiring location");
   }


 navigator.geolocation.watchPosition(onSuccess, onError, { enableHighAccuracy: true });
}

To really understand what this read this blog post http://dmitrysoshnikov.com/ecmascript/chapter-3-this/


Try to define onSuccess like this:

this.onSuccess = (function(locations) {
    return function(position)
           {
               alert("Entered onSuccess");
               alert("this.locations defined: " + locations);
           }
})(this.locations);
0

精彩评论

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