我是第一次用JavaScript编写一个类,我在将新数据写入类变量时遇到了一些麻烦。我已经尝试了好几个小时,但似乎什么都没有用!
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);
}
那么,我做错了什么?为什么变量没有更新到新值?
答案 0 :(得分:0)
当你写下:
authCallback(data);
然后在authCallback
内你将得到this
的错误值,它将是null
或全局对象(取决于你是否处于严格模式)
使用:
success: authCallback.bind(this)
确保回调中的this
实际上代表您的对象。
您还应注意,在回调完成之前,您无法访问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);
});