gpt4 book ai didi

javascript - Javascript 对象中的意外作用域行为

转载 作者:行者123 更新时间:2023-11-30 09:35:17 26 4
gpt4 key购买 nike

我尽力在我的上下文之外复制错误但失败了,所以我必须提供它。

代码:

var view;

widget = {
activated: false,
close: function(){
this.view.popupManager.enabled = false;
}
}

view = new MapView({
}).then(function(){ //then is triggered when fully loaded;
console.log(this.popupManager) //Object!
widget.activated = true;
widget.view = this;
}

console.log(view.popupManager) //Undefined, not loaded yet

$('#my_button').click(function(){
if(widget.activated){
widget.close() //this.view.popupManager is undefined
}
})

这是使用 Esri 的 Javascript 4.3 API,但它似乎不是 API,而是我对范围在 Javascript 中的工作方式的一些误解。

如您所见,即使我只在 view 完全加载时调用 widget.close,它仍然引用旧的、未完全加载的对象

我错过了什么?

最佳答案

这里的问题是this 并不总是您认为的那样。您的代码中有几个 this,每个都不一样。

欢迎来到 JavaScript 经常被误解的 this

在代码中

widget = {
activated: false,
close: function(){
this.view.popupManager.enabled = false;
}
}

this 将引用 widget

现在在 then 回调中的代码中,this 将引用 window 对象,所以您实际上是在说 widget.view = 窗口。这个 this 可能就是让你脱颖而出的那个。

我怀疑你的意思是将小部件的 View 设置为新 View ,在这种情况下你需要更新代码如下:

var view;

widget = {
activated: false,
close: function (){
this.view.popupManager.enabled = false;
}
}

view = new MapView({
}).then(function () {
widget.activated = true;
widget.view = view; // set the widget's view correctly
});

$('#my_button').click(function(){
if(widget.activated){
widget.close();
}
});

关于javascript - Javascript 对象中的意外作用域行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43900982/

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