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();
    
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度