Javascript-форум (https://javascript.ru/forum/)
-   Общие вопросы Javascript (https://javascript.ru/forum/misc/)
-   -   указатель this (https://javascript.ru/forum/misc/18385-ukazatel.html)

cmygeHm 28.06.2011 18:08

указатель this
 
Hello world!
Научите! как быть. Тут и JavaScript и JQuery.
Тема названа так, потому что другого названия придумать не мог. Также жду Ваших вариантов - как можно было назвать тему.
Имеем:
function MyObj () {

    this.func1 = function() {
        console.log(5);
    }
    
    this.func2 = function() {
        this.func1();
    }
    
    this.func3 = function(b) {
        console.log(b);
    }
    
    this.doAjax = function(fn) {
       
       $.ajax({
           url: '/mashines/index/getmashines/format/json',
           dataType: 'json',
           data: {'start': 0, 'limit': 50},
           assync: false,
           success: function(data) {
               fn(data);
           }

        });
   }
   
   this.errorFunc = function() {
       this.doAjax(function(a){
           console.log(a); // выводит отлично!
           this.func3(a); /* а здесь ошибка:
                      Uncaught ReferenceError: func3 is not defined - если без this обращаюсь к func3 и 
                      Object [object DOMWindow] has no method 'func3' - если через this*/
       });
   }
}


var myObj = new MyObj();
myObj.func1(); // вызывается отлично
myObj.func2() //вызывается отлично
myObj.errorFunc(); // бум!


Как я понимаю, при обращении к this.func3 внутри анонимной функции я обращаюсь к this объекта аjax. Там функция func3 не находится и он ищет в prototype объектов выше, и доходит до window! А там его тоже нет! Как же обратиться к методу??? Можно извращаться, но это по-моему не дело:

this.doAjax = function(fn) {
       var self = this;  // сохраняем this в self
       $.ajax({
           url: '/mashines/index/getmashines/format/json',
           dataType: 'json',
           data: {'start': 0, 'limit': 50},
           assync: false,
           success: function(data) {
               // и передаем его в fn
               fn(self, data);
           }

        });
   }
   
   this.errorFunc = function() {
       this.doAjax(function(mySelf, a){
           console.log(a);
           mySelf.func3(a);
       });
   }

NoResponse 28.06.2011 18:17

например так
function MyObj () {
var self = this;
...
self.func3(a);

cmygeHm 28.06.2011 18:20

ну как-то так... так себе...;) близко к тому, что я предложил. а есть еще что-нибудь?

nikita.mmf 28.06.2011 18:59

Можно так
$.ajax({
           url: '/mashines/index/getmashines/format/json',
           dataType: 'json',
           data: {'start': 0, 'limit': 50},
           assync: false,
           success: fn,
           context: this
        });

либо вот так
this.doAjax($.proxy(function(a){
           console.log(a); // выводит отлично!
           this.func3(a); 
       }, this));

cmygeHm 29.06.2011 11:20

ага! :) сейчас затестим :) спасибо всем :)


Часовой пояс GMT +3, время: 23:45.