2013-09-09 3 views
2

Я написал несколько объектно-ориентированный Javascript, как это:Javascript (прототип) вызов метода из обратного вызова Ajax

function MyClass(){ 

    this.SomeFunc(arg1){ 
     result = <some processing on arg1>; 
     return result; 
    }; 

    this.SomeOtherFunc(){ 
     return $.ajax({ 
      <some restful call> 
     }).done(function(){ 
      var localvar = this.SomeFunc(<value obtained by restful call>); 
      <some operations with localvar>; 
     }); 
    }; 
}; 

var myObj = new MyClass(); 
myObj.SomeOtherFunc(); 

И я получаю сообщение об ошибке в веб-консоли: «this.SomeFunc не является функцией». Если я вызываю его внутри функции напрямую, проблем нет. Вызов завершается только внутри Ajax. Каким будет правильный способ вызова этой функции?

+0

Может захотеть использовать ['var self = this;'] (http://stackoverflow.com/questions/962033/what-underlies-this-javascript-idiom-var-self-this) и упростить сам. В JavaScript может быть иная концепция. –

ответ

4

this в функции обратного вызова отличается от this со ссылкой на SomeFunc, попробуйте сделать:

this.SomeOtherFunc(){ 
    var thatFunc = this; //get hold of this 
    return $.ajax({ 
     <some restful call> 
    }).done(function(){ 
     var localvar = thatFunc.SomeFunc(<value obtained by restful call>); 
     <some operations with localvar>; 
    }); 
}; 
+0

Работал как очарование! Спасибо! :) –

0

Поскольку вы используете JQuery, вы можете убедиться в методе $ .proxy (http://api.jquery.com/jQuery.proxy/), который позволяет вам перейти в контекст. Например, вы могли бы сделать

this.SomeOtherFunc(){ 
    return $.ajax({ 
     <some restful call> 
    }).done($.proxy(function(){ 
     var localvar = thatFunc.SomeFunc(<value obtained by restful call>); 
     <some operations with localvar>; 
    }, this)); // Pass in what 'this' should be in method 
}; 

Здесь функция обратного вызова будет выполняться с this ссылки на объект, переданный в качестве второго параметра.

$.proxy(function(){ 
    // do stuff here 
}, this); 
0

Think первичной функции MyClass ваш конструктор. Это значит, что вы должны указать SomeFunc, но вы его вызываете. Это проблема, проявленная в консоли.

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

function MyClass(){ 
    // ----------vvvvvvvvvvv was missing 
    this.SomeFunc = function(arg1) { 
    result = <some processing on arg1>; 
    return result; 
    }; 

    // ---------------vvvvvvvvvvv same here 
    this.SomeOtherFunc = function() { 
    var _this = this 
    return $.ajax({ 
     <some restful call> 
    }).done(function(){ 
     // ------------v use _this instead of _this 
     var localvar = _this.SomeFunc(<value obtained by restful call>); 
     <some operations with localvar>; 
    }); 
    }; 
}; 

var myObj = new MyClass(); 
myObj.SomeOtherFunc(); 

Другой способ определения функций с помощью прототипа:

MyClass = function() { ... } 
MyClass.prototype.SomeFunc = function(arg1) { 
    return <some processing on arg1> 
} 
MyClass.prototype.SomeOtherFunc = function() { 
    var _this = this 
    return $.ajax({ ... }).done(function(data) { 
    _this.SomeFunc(data) 
    }) 
} 

Основное различие заключается в , что создание функций в конструкторе создаст новый function для каждого вызова new MyClass.

Надеюсь, что это поможет.

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