2012-03-11 2 views
1

개체가 myObject이고 내부에 execute()의 기능이 있고 $.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와 프록시를 확인 및/또는