2013-06-18 124 views
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.attributereq.done範圍有多大?如何訪問req.done內部的整個Bubble對象?目前,所有我Bubble S的是一個數組,所以我可以只通過在這個數組的索引和訪問屬性這樣(array[i].attribute)。我想有一個更好的方法來做到這一點。

+0

你試過背景:這一點,因爲阿賈克斯的選擇嗎?不知道它的工作原理在這種情況下 –

+1

'this'需要保存在某個地方'$。阿賈克斯()'函數外部的變量。 'var self = this;'那麼你可以使用'self'來訪問'this'。 –

回答

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

    }); 

} 
+0

這是最好的解決方案,接受。謝謝! – Saturnix

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 
    }); 
} 
+0

工作正常,謝謝! – Saturnix

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 

    }); 

} 
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 

}); 

} 
+1

您在全局範圍內設置_this,這裏不是最好的方法 –