Questions related to JavaScript object literal and google map API -
this code not working expected. trying use google geolocation api figure out current location. however, when try log result google.maps.latlng object, got (0,0) latitude , 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, code underneath works. did changing "this" keyword object's name. shouldn't make 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 not sure why code snippet on top produces incorrect output? not familiar objected oriented javascript. appreciate if me understand going on.
in first example, when call:
getcurrentposition(this.success, this.error); you merely passing success , error functions getcurrentposition. though reference them here via this, not carried through point functions called. passes function references themselves, not this value using here.
another way understand problem: value of this inside function determined at time function called. when write foo.bar() calling bar() function foo this value inside function. when write foo.bar without (), getting reference bar itself. foo out of picture after that. if pass foo.bar function expects callback, when calls bar() there no longer association foo.
that's why second example works. not depend on this uses func valid throughout outer function.
Comments
Post a Comment