【问题标题】:Call wrapper function from inside jQuery AJAX complete function从 jQuery AJAX 完整函数内部调用包装函数
【发布时间】:2022-02-07 21:05:58
【问题描述】:

这就是我正在尝试做的事情,但是我遇到了一个无法绑定到未定义的错误,我假设是因为我在一个匿名函数中。我需要访问 AJAX 调用所在的方法 (getAndSayHi)。

var Parent() = new Function () {
    this.sayHi = function (name) {
        console.log("hello " + name);
    }
    this.getAndSayHi = function () {
        $.ajax({
            ....
            success: function(data) {
                this.sayHi.bind(this, data);
            }
        });
    }

我怎样才能做到这一点?

【问题讨论】:

    标签: javascript jquery ajax


    【解决方案1】:

    试试

    this.getAndSayHi = function () {
        var parent = this;
        $.ajax({
            ....
            success: function(data) {
                parent.sayHi.bind(this, data);
            }
        });
    }
    

    【讨论】:

    • 你可能会解释为什么:this 总是指当前对象实例。在成功函数中,this 指的是 jQuery 对象,而不是您的 Parent 对象。因此,被调用的方法是未定义的。
    猜你喜欢
    • 2011-11-15
    • 2021-10-15
    • 1970-01-01
    • 2014-07-31
    • 2016-04-07
    • 2017-03-05
    • 1970-01-01
    • 1970-01-01
    • 2012-05-03
    相关资源
    最近更新 更多