Javascript变量在类之外未定义

时间:2014-09-25 09:31:06

标签: javascript class oop

我对Javascript OOP相对较新,并且一直在尝试构建一个类来处理我的应用程序中的某些功能。 我遇到的问题是,在我初始化了我的类之后,它在构造函数中设置了一些值,当我调用该类的一个函数时,它应该更新该实例中的一些变量并返回它们,这些变量是在未定义的外部传递的实例。 这是我的代码:

//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();

当我尝试从实例外部访问'this.latLng'变量时,它表示它是未定义的。当我从'setLatLng'函数中记录数据时,它被正确定义和输出,虽然这让我觉得这是一个封装问题? 谁能给我一些建议,为什么会出现这种情况? 感谢

1 个答案:

答案 0 :(得分:1)

通过将this设置为变量并在Geocoders回调中使用

来保持对原型“this”的引用
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);
        }               
    });
}