0

我在 javascript 中声明了一个对象方法。在这个方法内部,我想做一个 ajax 调用,并在调用完成后修改这个对象的一些属性。

Bubble.prototype.draw = function(){

console.log(this.attribute) // -> works fine

var req = $.ajax({
url: "someFile.php",
type: "post",
data: someData  
});

// handle response
req.done(function (response, textStatus, jqXHR){

console.log(this.attribute) // -> not in the scope, obviously

});

}

我怎样才能把this.attribute范围req.done?如何访问Bubble内部的整个对象req.done?目前,我所有的Bubbles 都在一个数组中,所以我可以传入这个数组的索引并以这种方式访问​​属性(array[i].attribute)。我想有一个更好的方法来做到这一点。

4

4 回答 4

3
Bubble.prototype.draw = function () {
    console.log(this.attribute) // -> works fine
    var req = $.ajax({
        url: "someFile.php",
        type: "post",
        data: someData
    }),
        self = this; //save this object
    // handle response
    req.done(function (response, textStatus, jqXHR) {
        console.log(self.attribute) //access parent this
    });
}
于 2013-06-18T12:21:00.137 回答
3

这是因为调用 ajax 回调时执行上下文不同,这意味着this回调方法中的关键字指向另一个对象,而不是所需的气泡对象。

有两种解决方案,如下所示

使用 $.proxy 将自定义执行上下文传递给回调处理程序

Bubble.prototype.draw = function(){

    console.log(this.attribute) // -> works fine

    var req = $.ajax({
        url: "someFile.php",
        type: "post",
        data: someData  
    });

    // handle response
    req.done($.proxy(function (response, textStatus, jqXHR){

        console.log(this.attribute) // -> not in the scope, obviously

    }, this));

}

或者使用闭包变量

Bubble.prototype.draw = function(){

    console.log(this.attribute) // -> works fine

    var req = $.ajax({
        url: "someFile.php",
        type: "post",
        data: someData  
    });

    var _this = this;
    // handle response
    req.done(function (response, textStatus, jqXHR){

        console.log(_this .attribute) // -> not in the scope, obviously

    });

}
于 2013-06-18T12:21:10.033 回答
1

只需将变量复制this.attribute到另一个范围变量,就像这样。

Bubble.prototype.draw = function(){

console.log(this.attribute) // -> works fine
_this = this.attribute;
var req = $.ajax({
url: "someFile.php",
type: "post",
data: someData  
});

// handle response
req.done(function (response, textStatus, jqXHR){

console.log(_this) // -> not in the scope, obviously

});

}
于 2013-06-18T12:23:42.687 回答
1

看起来它是这样工作的,这似乎是使用上下文选项的原生方式:

Bubble.prototype.draw = function () {

    console.log(this.attribute) // -> works fine

    var req = $.ajax({
        url: "someFile.php",
        type: "post",
        data: someData,
        context: this
    });

    // handle response
    req.done(function (response, textStatus, jqXHR) {

        console.log(this.attribute);

    });

}
于 2013-06-18T12:32:23.890 回答