James
James

Reputation: 2860

Javascript variable undefined outside of class

I am relatively new to Javascript OOP and have been attempting to build a class to handle some functionality within my application. The issue I am having is that after I have initialized my class, which sets some values in the constructor, when I call a function of that class which should update some variables within that instance and return them, these variables are coming through as undefined outside of the instance. Here is my code:

//Google Maps Javascript class
    var googleMapsFunctions = function(clubs, location) {
        this.clubs = clubs;
        this.location = location;
        this.latLng = new Array();
        this.geocoder = new google.maps.Geocoder();
        this.closeClubs = [];
    }

    googleMapsFunctions.prototype.setLatLng = function() {
        this.geocoder.geocode({'address' : this.location}, function(results, status) {
            if(status === "OK") {                                   
                this.latLng.push(results[0].geometry.location.k);
                this.latLng.push(results[0].geometry.location.B);
            }               
        });
    }       

    googleMapsFunctions.prototype.calculateDistances = function() {
        var sortable = [];
        var resultsArray = new Array();
        try {
            //alert(this.latLng);
        } catch(error) {
            alert(error);
        }
    }


    //Client code
    var JSONItems = <?php echo $this->JSONItems; ?>;        
    var searchTerm = "<?php echo $this->searchTerm; ?>";

    var googleMapsClass = new googleMapsFunctions(JSONItems, searchTerm);
    googleMapsClass.setLatLng();        
    googleMapsClass.calculateDistances();

When I try and access the 'this.latLng' variable from outside of the instance, it is saying that it is undefined. It is defined and outputting correctly when I log the data from within the 'setLatLng' function though which makes me think this is an encapsulation issue? Can anybody give me some advice as to why this may be occuring? Thanks

Upvotes: 0

Views: 1019

Answers (1)

Pete TNT
Pete TNT

Reputation: 8403

Keep the reference to the prototypes "this" by setting this to an variable and using it inside the Geocoders callback

var googleMapsFunctions = function(clubs, location) {
    this.clubs = clubs;
    this.location = location;
    this.latLng = new Array();
    this.geocoder = new google.maps.Geocoder();
    this.closeClubs = [];
}

googleMapsFunctions.prototype.setLatLng = function() {
    var that = this;
    this.geocoder.geocode({'address' : this.location}, function(results, status) {
        if(status === "OK") {                                   
            that.latLng.push(results[0].geometry.location.k);
            that.latLng.push(results[0].geometry.location.B);
        }               
    });
}       

Upvotes: 1

Related Questions