【问题标题】:Scope in asynchronous calls in JavascriptJavascript中异步调用的范围
【发布时间】:2012-10-04 03:35:57
【问题描述】:

我有下面的代码来定义一个类

var class1 = function () {
    this.classData = 'value1';
    this.func1 = function(callback) {
        $.ajax({
            'url': '/somewhere',
            'dataType': 'json',
            'type': 'POST',
            'data': {
                options: 'some text'
            },
            'success': function (data, textStatus, jqXHR) {
                callback(data); // <<<<<< THIS LINE
            }
        });
    };
};

然后我这样调用类

var obj1 = new class1();
obj1.func1(function (d) {
    this.classData = d;
});

但这似乎不起作用,因为在 sucess 函数内部,当在上面代码中标记的行调用回调函数时,它的 this 对象指向 window 而不是 @ 987654325@值。

我在这里做错了什么,我该如何解决?

【问题讨论】:

    标签: javascript jquery oop asynchronous scope


    【解决方案1】:

    这实际上不是范围问题,而是上下文问题。 this,当你的函数被调用时,是调用时函数的接收者,而不是对象obj1

    这样做:

    var obj1 = new class1();
    obj1.func1(function (d) {
        obj1.classData = d;
    });
    

    这是正确的方法。

    如果您的回调都意味着将 class1 的实例作为接收者,您也可以这样做:

    var class1 = function () {
        this.classData = 'value1';
        var _this = this;
        this.func1 = function(callback) {
            $.ajax({
                'url': '/somewhere',
                'dataType': 'json',
                'type': 'POST',
                'data': {
                    options: 'some text'
                },
                'success': function (data, textStatus, jqXHR) {
                    _this.callback(data); // note that I call the callback on the instance of obj1
                }
            });
        };
    };
    

    【讨论】:

    • 问题是我希望我的 this 成为 class1 对象的正确实例......所以如果我有多个对象实例......那么我希望回调编辑它已被调用!
    • 我的建议有问题吗?无论如何,我添加了一个替代方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-23
    • 1970-01-01
    • 2016-03-07
    • 1970-01-01
    • 2012-01-02
    • 1970-01-01
    • 2010-10-25
    相关资源
    最近更新 更多