javascript - why does is 'this' the DomWindow object when executing the google maps directions service callback -


so have object defined (simplified):

maproute : {             isinit : false,             latlang : "",             directionsservice :  null,             directionsrenderer : null,              init : function() {                 if(!this.isinit) {                     this.directionsservice = new google.maps.directionsservice();                     this.directionsrenderer = new google.maps.directionsrenderer();                     this.directionsrenderer.setpanel(document.getelementbyid("google_route_results"));                     this.isinit = true;                 }             },                 planroute : function() {                 var from;                 var to;                  = $('#addressfrom').val();                 = this.latlang;                  var directionsrequest = {                     origin:from,                     destination:to,                     travelmode: google.maps.directionstravelmode.driving                 };                  this.directionsservice.route(directionsrequest, this.planroutecallback);             },              planroutecallback : function(result,status){                 if(status == google.maps.directionsstatus.ok) {                     this.directionsrenderer.setdirections(result);                     this.directionsrenderer.setmap(google_map_object);                 } else {                     this.handleerrors(status);                 }             },              //handleerrors             handleerrors : function(statuscode) {                 //do stuff             },           }//end maproute 

however, when planroutecallback execute, errors because 'this' refers domwindow object, not maproute object. why case, , there can it?

the problem function being executed not within context of maproute object. example:

var foo = {bar: 10, fn: function(){ alert(this.bar); }}; foo.fn(); // called within context of object foo, alerts 10  var nocontextfn = foo.fn; nocontextfn(); // uh oh, no context, alerts undefined 

when pass callback maproute.planroutecallback other functions, have reference right functions, won't execute callback in context of maproute, above.

you create anonymous function , use self=this pattern every time pass callbacks parameters, although you're better off fixing function once , all. can bind function. after maproute object has been built, can run:

maproute.planroutecallback = maproute.planroutecallback.bind(maproute);

(note, bind() might not implemented in browsers, see mdc implementation can use).


Comments