2012-03-11 44 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的代理服務器和/或綁定