zoukankan      html  css  js  c++  java
  • 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里边当然不是一个函数了,人家没有报错错误,一个教训,一点经验!

  • 相关阅读:
    delphi7下调用微软的Web Services的心得
    Asp.net组件设计浅论
    STC系统烧写及STC12C5A60S2最小系统
    ENET 1.3.3 VC2005 下使用
    ENet library compilation record
    51定时器
    可靠的UDP编程(ENET库)
    ASP.NET MVC3布局页与分布页调用方式概述
    排除JQuery通过HttpGet调用WebService返回Json时“parserror”错误
    AJAX数据源协调处理思路
  • 原文地址:https://www.cnblogs.com/joe235/p/1138150.html
Copyright © 2011-2022 走看看