2014-09-25 50 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