Javascript jQuery更新类变量值不起作用
我第一次用JavaScript编写一个类,在向类变量写入新数据时遇到了一些问题。我已经试了好几个小时了,但似乎什么都不管用Javascript jQuery更新类变量值不起作用,javascript,ajax,class,oop,variables,Javascript,Ajax,Class,Oop,Variables,我第一次用JavaScript编写一个类,在向类变量写入新数据时遇到了一些问题。我已经试了好几个小时了,但似乎什么都不管用 function ClassName(productId) { //create variables this.productId = productId; this.shop = []; this.product = []; //method that calls for response. On success will retu
function ClassName(productId) {
//create variables
this.productId = productId;
this.shop = [];
this.product = [];
//method that calls for response. On success will return {"status" : "success", "shop" : "someshop.com"}
this.auth = function() {
$.ajax({
url: "http://website.com/api/auth/",
dataType: "jsonp",
success: function(data) {
authCallback(data); //use callback to handle response
},
error: function() {
console.log("bad auth");
}
});
}
var authCallback = function(r) {
//using console.log(r) output the response OK
this.shop = r; //this runs with no errors
}
}
现在,正如您在authCallback方法中看到的,我正在设置this.shop=r
但是如果我再次引用这个变量,它的默认值仍然是[]
var class = new ClassName(1);
class.auth();
console.log(class.shop); //this outputs []
在Javascript控制台中,我也尝试过在每个阶段完成后编写每一行代码(等待class.auth()
的响应和authCallback()
的输出,然后调用console.log(class.shop);
那么,我做错了什么?为什么变量没有更新到它的新值?当您只写:
authCallback(data);
然后在authCallback
中,您将获得错误的this
值,它将是null
或全局对象(取决于您是否处于严格模式)
使用:
确保回调中的这个实际上代表您的对象
您还应该注意,在回调完成之前,您无法访问this.shop
。使用现代jQuery技术的更惯用实现是:
this.auth = function() {
return $.ajax({
url: "http://website.com/api/auth/",
dataType: "jsonp"
}).done(this.authCallback.bind(this)).fail(function() {
console.log("bad auth");
});
};
this.authCallback = function(r) {
this.shop = r;
return this;
}
其次是:
var clazz = new ClassName(1);
clazz.auth().then(function(c) {
console.log(c.shop);
});
AJAX是异步的。在调用回调之前,您正在调用console.log()
。@Barmar,正如我在后面的问题中提到的,我尝试等待,然后在javascript控制台中编写console.log(),仍然不走运。trythis.authCalback=function(r){…}
,authCallback
应该是你的类的成员。你也有@Alnitak在回答中提到的这个问题。@KingKing这是不够的,因为上下文是在调用函数时设置的。函数是否真的是“类”的成员无关紧要或者没有。哦,我的天啊,太感谢你了!这太好了!!对于将来看到这个问题的人来说,同样的问题,上面的代码不起作用。他/她把.done(authCallback.bind(this))
改成.done(this.authCallback.bind(this))
而且它工作得很好!@user3228693我已经解决了这个问题-在我将.authCallback
作为类方法之前,它是正确的。
var clazz = new ClassName(1);
clazz.auth().then(function(c) {
console.log(c.shop);
});