gpt4 book ai didi

Javascript 变量在类外未定义

转载 作者:行者123 更新时间:2023-12-03 11:46:15 25 4
gpt4 key购买 nike

我对 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();

当我尝试从实异常(exception)部访问“this.latLng”变量时,它说它未定义。当我从“setLatLng”函数中记录数据时,它被定义并正确输出,但这让我认为这是一个封装问题?有人能给我一些关于为什么会发生这种情况的建议吗?谢谢

最佳答案

通过将 this 设置为变量并在 Geocoders 回调中使用它来保留对原型(prototype)“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);
}
});
}

关于Javascript 变量在类外未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26035094/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com