2012-03-11 45 views
1

我有对象myObject,里面我有功能​​,里面我有$.ajax({其中有complete: function(xmlHttp){。在那个函数里我想调用myObject中定义的setResult。怎么做?JavaScript面向对象与jQuery

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

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

回答

6

标准的方式做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使它成为该对象或使用其他方式绑定上下文

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的代理服务器和/或绑定