先看一段代码:
var tst = {
obj:null,
fun:function(){this.obj();}
};
tst.obj = function(){alert('hello,world');};
tst.fun();
obj:null,
fun:function(){this.obj();}
};
tst.obj = function(){alert('hello,world');};
tst.fun();
没任何问题,可以正常运行.
那么再看下边这个(典型AJAX应用):
var ajax = {
initHttp:function() {
if (window.XMLHttpRequest) {
doc = new XMLHttpRequest();
}
if(window.ActiveXObject) {
doc = new ActiveXObject("Microsoft.XMLHTTP");
}
},
queryString:null,
sendRequest:function(page,method) {
if (typeof(doc) != 'object') {
this.initHttp();
}
doc.open(method, page, true);
if ('POST' == method) {
doc.setRequestHeader("Content-type","application/x-www-form-urlencoded");
}
doc.send(this.queryString);
doc.onreadystatechange = function() {
if(doc.readyState == 4 && doc.status==200) {
this.processResult(); //注意这里
}//end if
}//end doc.onreadystatechange
},
processResult:null //回调函数
};
ajax.queryString = 'wife=晓宇';
ajax.processResult = function(){alert('aaa');};
ajax.sendRequest('test.php','GET');
initHttp:function() {
if (window.XMLHttpRequest) {
doc = new XMLHttpRequest();
}
if(window.ActiveXObject) {
doc = new ActiveXObject("Microsoft.XMLHTTP");
}
},
queryString:null,
sendRequest:function(page,method) {
if (typeof(doc) != 'object') {
this.initHttp();
}
doc.open(method, page, true);
if ('POST' == method) {
doc.setRequestHeader("Content-type","application/x-www-form-urlencoded");
}
doc.send(this.queryString);
doc.onreadystatechange = function() {
if(doc.readyState == 4 && doc.status==200) {
this.processResult(); //注意这里
}//end if
}//end doc.onreadystatechange
},
processResult:null //回调函数
};
ajax.queryString = 'wife=晓宇';
ajax.processResult = function(){alert('aaa');};
ajax.sendRequest('test.php','GET');
貌似跟上边的调用一模一样!却始终出这么个错误: this.processResult is not a function,奶奶滴,真是邪了!
我调试一个多钟头大概,把目光放到了这行"doc.onreadystatechange = function() {",注意,这句和上边的fun:function(){...是不同的,前者为赋值后调用,耳后者是直接调用,那么回头想一下,所谓的this.processResult到底是哪个this?
哈,我吧this改成了ajax.processResult重新运行了一遍,狂笑!,小样,到底让我搞明白了,此this非彼this,这里的this指的是“doc”这个对象,而不是ajax这个对象(说对象或许不太合适!-_-)。所以类,this.processResult在doc里边当然不是一个函数了,人家没有报错错误,一个教训,一点经验!