[英]OOP with Javascript and callback function
不知道如何制定问题所以如果你愿意,可以随意改变它。
那我的代码出了什么问题?
(function() {
//--> DOM is ready
var _$ = {
g: function(u,c){ // c is callback function
x=new XMLHttpRequest();
x.onreadystatechange = function(c){ // same c isn't it?!
d="", e=null;
if (x.readyState==4) {
if (x.status==200) { d = x.responseText; }
else { e = x.statusText; }
c(e,d); // how come c is an object
// and not a function here?!
}
}
x.open("GET",u,true); x.send(null);
}
}
//--> Call our method:
_$.g("http://copy.com/K8UjOnVoyUCiNmPC/qcm/0/1/2.json",
function(e,d){
if(!e){
window.alert(d);
}
}
);
//--> .DOM
})();
有什么线索我在这里错过了什么? 怎么做对了?
谢谢!
实际上,您并没有将相同的c
传入x.onreadstatechange
函数,而是定义了一个由onreadystatechange
事件指定的参数。 这是你需要做的:
.
.
.
var _$ = {
g: function(u, c) {
x = new XMLHttpRequest();
x.onreadystatechange = function() { // <== REMOVE: c as parameter
d = "", e = null;
if (x.readyState == 4) {
if (x.status == 200) { d = x.responseText; }
else { e = x.statusText; }
c(e, d); // Now c is the c that you passed into g
}
}
x.open("GET", u, true);
x.send(null);
}
}
.
.
.
问题是你的onreadystatechange回调中的c
是一个进度事件对象。 该问题的解决方案是简单地删除该参数,并让父方法_$.g
与它的c
参数提供一个闭包,让您可以像这样引用回调:
(function() {
//--> DOM is ready
var _$ = {
g: function(u,c){ // c is callback function
x=new XMLHttpRequest();
x.onreadystatechange = function(){ // same c isn't it?! No, it's a progress event object
d="", e=null;
if (x.readyState==4) {
if (x.status==200) { x.responseText; }
else { e = x.statusText; }
c(e,x.response); // how come c is an object
// and not a function here?!
}
}
x.open("GET",u,true); x.send(null);
}
}
//--> Call our method:
_$.g("http://copy.com/K8UjOnVoyUCiNmPC/qcm/0/1/2.json",
function(e,d){
if(!e){
window.alert(d);
}
}
);
//--> .DOM
})();
我希望这有帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.