如何将对象传递给 jquery 回调?

How pass object to jquery callback?

我有这个代码:

function API() {
    this.status = 'nothing';
}

API.prototype.search = function() {
    this.status = 'searching';

    $.ajax({
        url: 'https://api.com',
        data: {shapeFormat: 'raw'},
        dataType: 'json',
        timeout: 11000,
        success: this.OK_callback,
        error: this.KO_callback
    });
}

API.prototype.OK_callback = function(data) {
    console.log(this.status); // How to pass this value to the function?
}

API.prototype.KO_callback() {
    this.status = 'done';
}

我如何访问 this.status 值 insie OK_callback? 提前致谢!

您需要在适当的上下文中调用您的函数。简单的就是用Function.prototype.bind方法:

$.ajax({
    url: 'https://api.com',
    data: {shapeFormat: 'raw'},
    dataType: 'json',
    timeout: 11000,
    success: this.OK_callback.bind(this),
    error: this.KO_callback.bind(this)
});

或者您可以使用 context 设置来设置回调上下文:

$.ajax({
    url: 'https://api.com',
    data: {shapeFormat: 'raw'},
    dataType: 'json',
    timeout: 11000,
    success: this.OK_callback,
    error: this.KO_callback,
    context: this
});