【问题标题】:OOP with Javascript and callback function带有 Javascript 和回调函数的 OOP
【发布时间】:2014-04-19 04:37:59
【问题描述】:

不知道如何提出问题,所以如果您愿意,请随时更改。

那么我的代码有什么问题?

(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 与在第一行用 var 声明 c 相同函数:它创建一个新的局部变量c,它不引用“外部”c

标签: javascript ajax oop


【解决方案1】:

您实际上并没有将相同的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);
    }
}
.
.
.

【讨论】:

  • 谢谢你!成就了我的一天。我今天看到的代码太多了! XD 我会选择你的答案作为正确答案。 ;)
【解决方案2】:

问题在于 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
})();

我希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 2011-06-26
    • 1970-01-01
    • 1970-01-01
    • 2011-02-20
    • 2016-08-17
    • 1970-01-01
    • 1970-01-01
    • 2015-04-27
    • 1970-01-01
    相关资源
    最近更新 更多