title: Javascript: Callback function called from inside object method producing unexpected results
body: <p>I have a simple object called RouteLeg that contains a set of Lat/Lng values and has the ability to render a driving route between the two lat/lng points using the google maps api.</p>
  
  <p>In the renderRoad method I call the google maps api DirectionsService.route method, using closure on the callback function so that it has access to the RouteLeg object (self is an object member defined as self = this):</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>  
  
  directionsService.route(request, (function(obj) {
      return function(result, status) {
          if (status == google.maps.DirectionsStatus.OK) {
              obj.getDisplay().setDirections(result);
          }
      };
  })(self));</code></pre>
  </div>
  </div>
  </p>
  
  <p>The code only works if the <strong>display</strong> member variable of RouteLeg (a DirectionsRenderer object) is declared as private (var display) instead of public (this.display).  When display is declared as public it always has a value of null in the callback function. </p>
  
  <p>I'm relatively new to JS and do not understand this behavior.  What am I missing?</p>
  
  <p>(P.S. When I change the scope of the display variable I also change the this.getDisplay function to match.  directionsService and map are global variables). </p>
  
  <p><div class="snippet" data-lang="js" data-hide="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>function RouteLeg(aStart, aEnd) {
    var start = aStart; //an object that contains lat/lng values
    var end = aEnd; //lat/lng object
    this.display = null;  //does not work, only works as when declared as a var 
    var self = this;
  
    this.getDisplay = function() {
      return this.display;
    }
  
    this.render = function() {
      renderRoad();
    }
  
    var renderRoad = function() {
      if (this.display == null) {
        this.display = new google.maps.DirectionsRenderer({
          suppressMarkers: true
        });
      }
      this.display.setMap(map);
  
      var request = {
        origin: new google.maps.LatLng(start.getLat(), start.getLng()),
        destination: new google.maps.LatLng(end.getLat(), end.getLng()),
        travelMode: google.maps.TravelMode.DRIVING
      };
  
      //directionsService is a global variable for now
      directionsService.route(request, (function(obj) {
        return function(result, status) {
          if (status == google.maps.DirectionsStatus.OK) {
            obj.getDisplay().setDirections(result);
          }
  
        };
      })(self));
  
    }
  }</code></pre>
  </div>
  </div>
  </p>