Reputation: 343
This code is not working as expected. I am trying to use the Google Geolocation API to figure out my current location. However, when I try to log the result for the google.maps.LatLng object, I got (0,0) as the latitude and longitude coordinates.
$(document).ready(function(){
var func = {
lat:0,
long:0,
success:function(pos) {
var crd = pos.coords;
this.lat = crd.latitude;
this.long = crd.longitude;
},
error:function(err) {
console.log('ERROR(' + err.code + '): ' + err.message);
},
init:function(){
navigator.geolocation.getCurrentPosition(this.success, this.error);
}
};
func.init();
$('button').on('click',function(){
var loc = new google.maps.LatLng(func.lat, func.long);
alert(loc);
});
});
However, the code underneath works. All I did was changing "this" keyword to the object's name. It shouldn't make a difference.
$(document).ready(function(){
var func = {
lat:0,
long:0,
success:function(pos) {
var crd = pos.coords;
func.lat = crd.latitude;
func.long = crd.longitude;
},
error:function(err) {
console.log('ERROR(' + err.code + '): ' + err.message);
},
init:function(){
navigator.geolocation.getCurrentPosition(func.success, func.error);
}
};
func.init();
$('button').on('click',function(){
var loc = new google.maps.LatLng(func.lat, func.long);
alert(loc);
});
});
I am not sure why the code snippet on the top produces incorrect output? I am not too familiar with Objected Oriented JavaScript. I would appreciate it if anyone could help me understand what is going on.
Upvotes: 0
Views: 112
Reputation: 28870
In your first example, when you call:
getCurrentPosition(this.success, this.error);
You are merely passing the success
and error
functions into getCurrentPosition
. Even though you reference them here via this
, that is not carried through to the point where the functions are actually called. It only passes the function references themselves, not the this
value that you were using here.
Another way to understand the problem: the value of this
inside a function is determined at the time the function is called. When you write foo.bar()
you are calling the bar()
function with foo
as the this
value inside the function. But when you write foo.bar
without the ()
, you are only getting a reference to bar
itself. foo
is out of the picture after that. If you pass foo.bar
into another function which expects a callback, when it finally calls bar()
there is no longer any association with foo
.
That's why your second example works. It does not depend on this
but uses func
which is valid throughout the outer function.
Upvotes: 1