2012-03-11 7 views
1

私はオブジェクトmyObjectを持っていますが、内部には​​という機能があります。$.ajax({にはcomplete: function(xmlHttp){があります。この関数の中では、myObjectで定義されているsetResultを呼び出す必要があります。どうやってするか?jQueryを使用したJavaScript OOP

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のプロキシをチェックアウト、および/または

関連する問題