Javascript/jQuery对象作用域问题

Javascript/jQuery object scope issues

本文关键字:作用域 问题 对象 jQuery Javascript      更新时间:2023-09-26

我在JS中的作用域有一些问题,我刚刚捡起。

我已经定义了一个对象,并在其中进行。getjson()调用,但我似乎无法正确引用调用对象的属性:

// Vehicle object
function vehicle(id) {
    this.id = id;
    var that = this;
    // Fetch some JSON
    $.getJSON("json.php?act=vehicleInfo&id=" + this.id, function (json) {
        that.vehicleInfo = json
        that.icon = L.AwesomeMarkers.icon({ icon: that.vehicleInfo.icon, color: that.vehicleInfo.colour });
        that.polyline = new L.Polyline([[that.vehicleInfo.latitude, that.vehicleInfo.longitude]]);
        that.marker = L.marker([that.vehicleInfo.latitude, that.vehicleInfo.longitude], {icon: that.icon});
        that.marker.bindPopup("Test point");
        that.marker.addTo(map);
        that.polyline.addTo(map);
    });
}
// Vehicle move method
vehicle.prototype.move = function(latlng){
    this.marker.setLatLng(latlng);
    this.polyline.addLatLng(latlng);
}

当我调用。move()时,这。标记未定义。我哪里出错了?

不幸的是,Ajax不是这样工作的。您不能指望$.getJSON回调在任何特定时间完成,甚至根本不能指望它完成。一种可能性是使请求同步,但不推荐使用,因为这会锁定浏览器。

唯一可能的两个解是:

  1. 不依赖ajax
  2. 让任何依赖于ajax回调结果的东西依赖于回调本身。

这是任何代码调用.move为车辆必须做的$.getJSON调用的结果。不过,您可以让它看起来更优雅一点:

this.jqxhr = $.getJSON(...
/* snip */
vehicle.prototype.move = function (latlng) {
    var veh = this;
    this.jqxhr.done(function () {
       veh.marker.setLatLng(latlng);
       veh.polyline.setLatLng(latlng);
    });
}