Javascript - 从$ .post回调后,实例类的属性未定义

Jin*_* Ho 1 javascript jquery callback jquery-callback

我有以下js片段:

<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>
Run Code Online (Sandbox Code Playgroud)

它总是产生结果:之前:10之后:undefine.

为什么在$ .post的回调函数中,类的属性是未定义的.谁能帮助我?非常感谢.

Thi*_*ilo 7

success: this.callback
Run Code Online (Sandbox Code Playgroud)

这不行.您需要将回调绑定到实例(this).否则它将失去其范围.遗憾的是,单独的功能不会记住它.

手动方式是

var me = this;

// .....

success: function(x,y,z) { me.callback(x,y,z) }
Run Code Online (Sandbox Code Playgroud)

而我现在找不到jQuery的内置助手.在CoffeeScript中,您只需使用胖箭头=>.

更新:找到jQuery方式:有一个参数context可以指定$.ajax,并且将成为this所有回调:

 success:  this.callback,
 context:  this
Run Code Online (Sandbox Code Playgroud)