1

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

这是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);​
4

2 回答 2

5

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

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);

编辑我为此做了一个小提琴并验证它可以正常工作。没有乱用额外的self参数,也不必乱用闭包来保留你的变量。

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

于 2012-11-02T16:35:55.793 回答
3

我已更改您的代码以将引用传递给thisdoStuff() 代码。

(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,self);
                }
            });
            alert('doAjax1 self === c$.oTestScope: ' + (self === c$.oTestScope).toString());  
        };

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

    };

    c$.oTestScope = new c$.TestScope();
    c$.oTestScope.doAjax(c$.oTestScope.doStuff);
})(jQuery);​
于 2012-11-02T16:29:20.680 回答