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ですか? 現在、すべての はBubble配列内にあるため、この配列のインデックスを渡すだけで、この方法でプロパティにアクセスできます ( 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コールバック メソッド内のキーワードは、目的のバブル オブジェクトではなく、別のオブジェクトを指しています。

以下に示すように、これには2つの解決策があります

$.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 に答える