gpt4 book ai didi

javascript - 使用异步请求初始化对象

转载 作者:行者123 更新时间:2023-12-02 16:54:15 26 4
gpt4 key购买 nike

这是我的对象定义:

function DrilledLayer(sourceLayerName, sourceTableName, targetLayerName, targetFieldName, operators, baseLayer=false) {
this.sourceLayerName = sourceLayerName;
this.sourceTableName = sourceTableName;
this.targetLayerName = targetLayerName;
this.targetFieldName = targetFieldName;
this.operators = operators;
this.baseLayer = baseLayer;
this.targetLayerId;
this.drilledLayerId;
this.selectedCode;
this.redraw = false;

this.getTargetLayerId(); //this function must initialize this.targetLayerId
}

DrilledLayer.prototype.getTargetLayerId = function(){
$.soap({
url: 'https://url/version_4.8/services/MapService',
method: 'getLayersIdByName',
appendMethodToURL: false,
data : {
mapInstanceKey: mapKey,
layerName: this.targetLayerName,
},
error: function(){
alert("error getLayersIdByName");
},
success: function(soapResponse){
layerId = soapResponse.toJSON().Body.getLayersIdByNameResponse.getLayersIdByNameReturn.getLayersIdByNameReturn.text;
this.targetLayerId = layerId;
}
});
}

这就是我创建对象的方式:

drillCs = new DrilledLayer("Drilled CS", "Cs_Franco_General.TAB", "RA_General", "Code_RA", "=")

如果我查看drillCs对象,没有定义targetLayerId属性,但我知道soap请求已成功发出。为什么?

最佳答案

JavaScript 中的

this 主要是通过调用函数的方式来设置的。 success 回调期间的 this 不会与调用 getTargetLayerId 函数期间的 this 相同,您一定要记住。

在这种情况下,最简单的方法可能是使用变量:

DrilledLayer.prototype.getTargetLayerId = function(){
var layer = this; // <=== Set it
$.soap({
url: 'https://url/version_4.8/services/MapService',
method: 'getLayersIdByName',
appendMethodToURL: false,
data : {
mapInstanceKey: mapKey,
layerName: this.targetLayerName,
},
error: function(){
alert("error getLayersIdByName");
},
success: function(soapResponse){
layerId = soapResponse.toJSON().Body.getLayersIdByNameResponse.getLayersIdByNameReturn.getLayersIdByNameReturn.text;
layer.targetLayerId = layerId; // <=== Use it
}
});
}

更多(在我的博客上):

当然,在异步回调触发之前(这将在 new 调用返回后的一段时间),您不会正确看到,但您似乎对异步方面感到满意的这个。

关于javascript - 使用异步请求初始化对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26300613/

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