gpt4 book ai didi

javascript - 如何在 dojo/request promise 中检索类成员

转载 作者:行者123 更新时间:2023-11-30 18:08:42 25 4
gpt4 key购买 nike

我使用 dojo/reqeustdelcare 进行测试。

我声明了一个新类,其中包含一个将使用 dojo/request 进行查询的函数。在 promise 函数中,我无法检索到 this 成员。

   var TestJson = declare(null, {
name: "hello",
doJson: function(){
request.post("someTarget").then(function(res){
alert(this.name);
});
}
});

var obj= new TestJson();
obj.doJson();

如上,当 post 返回时,alert(this.name) 被调用。但是this指向的是Window对象,所以this.name是undefined,不是指向TestJson.name。那么如何检索 TestJson.name 呢?谢谢!

最佳答案

有几种方法可以解决这个问题。

在闭包作用域中引用一个变量:

var TestJson = declare(null, {
name: "hello",
doJson: function(){
var instance = this;
request.post("someTarget").then(function(res){
alert(instance.name);
});
}
});

使用dojo/_base/lang模块来set the execution context关于回调:

var TestJson = declare(null, {
name: "hello",
doJson: function(){
var callback = lang.hitch(this, function(res){
alert(this.name);
});
request.post("someTarget").then(callback);
}
});

关于javascript - 如何在 dojo/request promise 中检索类成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15155191/

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