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

  • 相关阅读:
    Ubuntu环境变量设置注意点
    在使用Vue2.0中使用axios库时,遇到415错误
    Eureka+SpringBoot2.X结合Security注册中心安全验证
    Eureka+SpringBoot2.X版本实现优雅停服
    Linux 解压xz格式文件及安装xz
    Linux gzip: stdin: not in gzip format
    SpringBoot配置文件yml ScannerException: while scanning an alias *
    java 实现文件下载中文名不显示
    连接SpringBootAdmin 异常 Name or service not known
    Idea环境实现SpringBoot实现两种热部署方式(亲测有效)
  • 原文地址:https://www.cnblogs.com/joe235/p/1138150.html
Copyright © 2011-2022 走看看