$.ajax 回调函数中的作用域 [英] Scope in an $.ajax callback function

查看:29
本文介绍了$.ajax 回调函数中的作用域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我使用此代码,为什么doStuff"警报的范围发生了变化?有没有办法确保作用域是我的对象而不是 Window 对象?

If I am using this code why has the scope changed for the "doStuff" alert? Is there a way that I can make sure that the scope is my object and not the Window object?

这是 jsfiddle 中的相同代码.

Here is the same code in jsfiddle.

(function ($) {
    var c$ = {};

    c$.TestScope = function () {

        this.doAjax = function (onComplete) {
            var self = this;
            $.ajax({
                url: 'badurl',
                complete: function (data) {
                    alert('doAjax2 self === c$.oTestScope: ' + (self === c$.oTestScope).toString());
                    onComplete(data);
                }
            });
            alert('doAjax1 self === c$.oTestScope: ' + (self === c$.oTestScope).toString());  
        };

        this.doStuff = function (data) {
            var self = this;
            alert('doStuff self === c$.oTestScope: ' + (self === c$.oTestScope).toString());
        }

    };

    c$.oTestScope = new c$.TestScope();
    c$.oTestScope.doAjax(c$.oTestScope.doStuff);
})(jQuery);​

推荐答案

您应该能够将 this 值指定为 $.ajax() 中的上下文参数:

You should be able to specify the this value as the context in your $.ajax() parameters:

var c$ = {};

c$.TestScope = function() {

    this.doAjax = function(onComplete) {

        alert('doAjax1 this === c$.oTestScope: ' + (this === c$.oTestScope).toString());

        $.ajax({
            url: 'badurl',
            context: this,
            complete: function(data) {
                alert('doAjax2 this === c$.oTestScope: ' + (this === c$.oTestScope).toString());
                onComplete.call(this, data);
            }
        });
    };

    this.doStuff = function(data) {
        alert('doStuff this === c$.oTestScope: ' + (this === c$.oTestScope).toString());
    }

};

c$.oTestScope = new c$.TestScope();
c$.oTestScope.doAjax(c$.oTestScope.doStuff);

编辑我为此做了一个 fiddle 并验证它有效适当地.无需处理额外的 self 参数,也无需使用闭包来保留变量.

Edit I made a fiddle for this and verified that it works properly. There's no messing around with an extra self parameter or having to muck around with closures to keep your variables.

您缺少的部分内容是调​​用 onComplete.call(this, data) 来调用 doStuff().

Part of what you were missing was calling onComplete.call(this, data) to invoke doStuff().

这篇关于$.ajax 回调函数中的作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆