admin管理员组

文章数量:1390262

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.

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.

Share Improve this question asked Nov 21, 2011 at 7:02 Jin HoJin Ho 3,6655 gold badges24 silver badges25 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 7
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 bee this for all callbacks:

 success:  this.callback,
 context:  this

You are loosing context so the this points to the different object. There is a build-in proxy function available in jQuery. Change your code as follows:

// ...
$.ajax({
    url: 'some-url',
    async: true,
    type: 'POST',
    dataType: 'json',
    success: $.proxy(this.callback, this)
});
// ...

The problem is due to the function closure. "this" for callback doesn't point to "test", instead to the callback function itself.

Use something like this

function binder (func, thisValue) {
            return function () {
                return func.apply(thisValue, arguments);
            }
        }

var bindedFun = binder(function () {
            alert('after: ' + this.a);
        }, test);

The other way to do this is to make the callback a local function that has access to local scope and save a reference to this in local scope. I think this could work fine because the callback may want access to this, but it doesn't necessarily have to be a method to do that.

    test.prototype.next = function () {
        var self = this;

        function callback() {
            alert('after: ' + self.a);
        }

        alert('before: ' + this.a);
        $.ajax({
            url: 'some-url',
            async: true,
            type: 'POST',
            dataType: 'json',
            success: callback

        });
    };

few changes in ur code like following will do

<script language="javascript">
          function test() {
            this.a = 10;
        };
        test.prototype.next = function () {
            alert('before: ' + this.a);
            var oThis = this;          //Save refernce of Test() function in a varaiable. then use it 
            $.ajax({
                url: 'some-url',
                async: true,
                type: 'POST',
                dataType: 'json',
                success: oThis.callback // This is change this=> earlier was referring 
                                        //$.ajax object so save this of test() 
                                        // in a variable and then use it 
            });
        };
        test.prototype.callback = function () {
            alert('after: ' + this.a);
        };

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

本文标签: jqueryJavascriptProperty of an instance class is undefined after callback from postStack Overflow