JavaScript回调函数陷阱

先看一段代码:

var tst  =   {
    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 ' );

貌似跟上边的调用一模一样!却始终出这么个错误: 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里边当然不是一个函数了,人家没有报错错误,一个教训,一点经验!

转载于:https://www.cnblogs.com/joe235/archive/2008/04/05/1138150.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值