【问题标题】:JavaScript OOP with jQuery带有 jQ​​uery 的 JavaScript OOP
【发布时间】:2012-03-28 07:56:21
【问题描述】:

我有对象myObject,里面有函数execute(),里面有$.ajax({,里面有complete: function(xmlHttp){。在该函数内部,我想调用在myObject 中定义的 setResult。该怎么做?

function myObject() {
    this.setResult = setResult;
    function setResult(result) {
        this.result = result;   
    }

    function execute() {
         $.ajax({
            complete: function(xmlHttp){
                (?) setResult(jQuery.parseJSON(xmlHttp.responseText));
            }
        });
    }

【问题讨论】:

    标签: javascript jquery oop


    【解决方案1】:

    执行 OOP 的标准方法是使用 myObject 作为构造函数,并使用需要继承的任何内容扩展其 prototype 对象。

    function myObject() {
        // constructor function
    }
    
    myObject.prototype.setResult = function (result) {
        this.result = result;   
    }
    
    myObject.prototype.execute = function() {
         $.ajax({
            context: this, // bind the calling context of the callback to "this"
            complete: function(xmlHttp){
                this.setResult(jQuery.parseJSON(xmlHttp.responseText));
            }
        });
    }
    
    var obj = new myObject();
    obj.execute();
    

    没有要求这样做,但这很常见。

    您需要记住,函数的调用上下文因调用该函数的方式而异。关于complete: 回调,jQuery 设置了上下文,所以它不会是你的对象,除非你告诉 jQuery 让它成为那个对象或使用其他方式来绑定上下文。 p>

    jQuery 的 $.ajax 方法为您提供了一个 context: 属性,可让您设置回调的调用上下文,如上所示。

    【讨论】:

      【解决方案2】:
      function myObject() {
          var that = this; // Reference to this stored in "that"
          this.setResult = setResult;
      
          function setResult(result) {
              this.result = result;   
          };
      
          function execute() {
               $.ajax({
                  complete: function(xmlHttp){
                      that.setResult(jQuery.parseJSON(xmlHttp.responseText));
              }
          });
      }
      

      您还可以查看 jquery 代理和/或绑定

      【讨论】:

        猜你喜欢
        • 2011-08-04
        • 2014-06-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-07-10
        • 1970-01-01
        • 2011-12-12
        • 2021-07-11
        相关资源
        最近更新 更多