2015-04-05 3 views
1

На самом деле мне нужно получить доступ к методу FileUploader.prototype.saveImage() как следующий код:как метод доступа объекта внутри Ajax успеха

function FileUploader(object) { 
    this.checkInputs(object); 
    if (this.isImageSelected()) { 
     this.beforeInit(object); 
     this.prepareData(); 
     this.uploadFile().success(function (response) { 
      var response = jQuery.parseJSON(response); 
      if (response.status != null && response.status) { 
       this.saveImage(response.data); 
      } else { 
       this.setError({ 
        error_code: 3, 
        error_message: " error found " 
       }); 
      } 
     }); 
    } 
} 

FileUploader.prototype.saveImage = function (data) { 
    ... 
} 

предыдущий вызов this.saveImage() возвращает ошибку

Uncaught TypeError: не определено не является функцией

кто-то может мне помочь, пожалуйста,

ответ

2

Если вы создаете анонимную функцию this будет объект окна, так что вам нужно, чтобы сохранить значение этого в переменной, как это:

function FileUploader(object) { 
    this.checkInputs(object); 
    if (this.isImageSelected()) { 
     this.beforeInit(object); 
     this.prepareData(); 
     var self = this; 
     this.uploadFile().success(function (response) { 
      var response = jQuery.parseJSON(response); 
      if (response.status != null && response.status) { 
       self.saveImage(response.data); 
      } else { 
       self.setError({ 
        error_code: 3, 
        error_message: " error found " 
       }); 
      } 
     }); 
    } 
} 

Или вы можете использовать привязку:

function FileUploader(object) { 
    this.checkInputs(object); 
    if (this.isImageSelected()) { 
     this.beforeInit(object); 
     this.prepareData(); 
     this.uploadFile().success(function (response) { 
      var response = jQuery.parseJSON(response); 
      if (response.status != null && response.status) { 
       this.saveImage(response.data); 
      } else { 
       this.setError({ 
        error_code: 3, 
        error_message: " error found " 
       }); 
      } 
     }.bind(this)); 
    } 
} 
+0

спасибо, это есть ли другая возможность прямого доступа без объявления переменной? – oofy

+1

@oofy вы можете связать функцию с этим – jcubic

Смежные вопросы