weixin_33735077 2015-01-12 00:19 采纳率: 0%
浏览 18

对象内部的回调

Why doesn't this work

I have an ajax function via jquery inside an object, and for some reason it's not seeing the other functions in the object inside the callback function.

function object () {

this.test = function () { alert ("test") }

this.makeQuery = function() {
$.ajax( { 
    url: stuff,
    dataType: "xml",
    success: function (data) {  makeData(data) } } )        

}   

this.makeData = function (data) {

  this.test();   // Error "this.test() is not a function"
}

}
  • 写回答

1条回答 默认 最新

  • 狐狸.fox 2015-01-12 00:32
    关注

    The reason is because callback functions are called with a different "this". In the case of the jQuery.ajax call, the "this" function is the jqXHR object http://api.jquery.com/Types/#jqXHR. So if you want to pass the "this" object into the callback you must capture it in the scope and the reference the captured variable. Like this (if I fix all your syntax errors):

    function myFunction() {
        var that = this;
        this.test = function () { alert ("test") };
    
        this.makeQuery = function() {
            jQuery.ajax({
                    type: 'post',
                    url: 'someUrl',
                    dataType: 'json',
                    success: function (data, textStatus, jqXHR) {
                        that.makeData(data);
                    },
                    error: function (jqXHR, textStatus, textError) {
                    }
                });
            };
    
        this.makeData = function(data) {
            this.data = data
            this.test();   // Error "this.test() is not a function"
        };
    }
    var m = new myFunction();
    m.makeQuery();
    
    评论

报告相同问题?