如何在ajax成功中访问对象方法

时间:2015-04-05 10:05:34

标签: javascript jquery ajax

实际上我需要访问 FileUploader.prototype.saveImage()方法 如下代码:

function FileUploader(object) {
    this.checkInputs(object);
    if (this.isImageSelected()) {
        this.beforeInit(object);
        this.prepareData();
        this.uploadFile().success(function (response) {
            var response = jQuery.parseJSON(response);
            if (response.status != null && response.status) {
                this.saveImage(response.data);
            } else {
                this.setError({
                    error_code: 3,
                    error_message: " error found "
                });
            }
        });
    }
}

FileUploader.prototype.saveImage = function (data) {
    ...
}

上一次调用this.saveImage()返回错误

未捕获的TypeError:undefined不是函数

请有人帮助我

1 个答案:

答案 0 :(得分:2)

如果你创建匿名函数this将是window对象,所以你需要将这个值存储在变量中,如下所示:

function FileUploader(object) {
    this.checkInputs(object);
    if (this.isImageSelected()) {
        this.beforeInit(object);
        this.prepareData();
        var self = this;
        this.uploadFile().success(function (response) {
            var response = jQuery.parseJSON(response);
            if (response.status != null && response.status) {
                self.saveImage(response.data);
            } else {
                self.setError({
                    error_code: 3,
                    error_message: " error found "
                });
            }
        });
    }
}

或者您可以使用bind:

function FileUploader(object) {
    this.checkInputs(object);
    if (this.isImageSelected()) {
        this.beforeInit(object);
        this.prepareData();
        this.uploadFile().success(function (response) {
            var response = jQuery.parseJSON(response);
            if (response.status != null && response.status) {
                this.saveImage(response.data);
            } else {
                this.setError({
                    error_code: 3,
                    error_message: " error found "
                });
            }
        }.bind(this));
    }
}