Search code examples
javascriptjquerycallbackjquery-callback

Javascript - Property of an instance class is undefined after callback from $.post


I have the following js snippet:

<script language="javascript">
          function test() {
            this.a = 10;
        };
        test.prototype.next = function () {
            alert('before: ' + this.a);
            $.ajax({
                url: 'some-url',
                async: true,
                type: 'POST',
                dataType: 'json',
                success: this.callback

            });
        };
        test.prototype.callback = function () {
            alert('after: ' + this.a);
        };

        $(document).ready(function () {
            var test1 = new test();
            test1.next();
        });
      </script>

It's alway produce result: before: 10 after: undefine.

Why in the callback function of $.post, properties of class are undefined. Could anyone help me? Thanks a lot.


Solution

  • success: this.callback
    

    This won't work. You need to bind the callback to the instance (this). Otherwise it will have lost its scope. The function alone will unfortunately not remember it.

    The manual way would be

    var me = this;
    
    // .....
    
    success: function(x,y,z) { me.callback(x,y,z) }
    

    and I cannot find the built-in helper that jQuery has for this right now. In CoffeeScript you'd just use the fat arrow =>.

    Update: found the jQuery way: There is a parameter context that you can specify for $.ajax, and that will become this for all callbacks:

     success:  this.callback,
     context:  this