2014-09-25 48 views
0

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

//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'函数中记录数据时,它被正确地定义和输出,但是这使我认为这是一个封装问题? 任何人都可以给我一些建议,为什么这可能会发生? 由于

+0

相关保持参考原型“this”:http://stackoverflow.com/questions/111102/how- do-javascript-closures-work?rq = 1 – 2014-09-25 09:43:51

+0

是的,这是封装。如果您需要访问实例内的变量,则应该添加访问该类中变量的方法。如果要获取latLng的数据,请添加方法getLatLng(),该方法返回类中latLng的值。 – 2014-09-25 09:45:13

+0

当您尝试访问实例的'latLng'属性时,您的JS看起来像什么?这可能是由'this'的上下文引起的(通常是通过调用函数'this'来设置上下文,比如说'window') – Jack 2014-09-25 09:48:31

回答

1

通过设置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); 
     }    
    }); 
}  
+0

非常感谢。 – devoncrazylegs 2014-09-25 10:06:55