[英]How to get “this.value” on jQuery.ajax
我正在使用文本編輯器在FireFox 11上編寫javascript。 在以下情況下,“ var n = this.val”變為“ undefined”。 如何在原始類對象中獲取局部值?
<html>
<body>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
var Test = {
val : 0,
begin: function(v){
this.val = v;
this.recieve();
},
complete: function(o){
var n = this.val; // undefined
},
recieve : function(){
$.ajax({
url : "http://www.yahoo.com/", // Dummy
type: "POST",
dataType: "json",
complete: this.complete,
timeout: 1000,
});
},
};
var c = Object(Test);
c.begin(10);
</script>
</body>
</html>
complete: this.complete.
bind(this)
這在舊的IE版本中將不起作用,但是經過一些努力(添加es5 shim
代碼),即使在那兒也可以使其工作。
complete
函數是在ajax請求的上下文中執行的。 如果您編寫這樣的代碼:
var method = Test.complete;
method();
this
不會保留,您只需獲取該函數的鏈接即可。 name1.name2()
在js中有技巧。 不僅name2
應該是name1
的屬性並且是一個函數,而且它(name2)也在name1
上下文中執行。
var x = 'outer', b = {
x: 'inner',
a: function() { return this.x; }
};
[(b.a)(), (m = b.a)()] // ["inner", "outer"]
因為complete
是一個回調的范圍已發生變化, this
並不指稱為對象Test
。 您只需要更換this
與Test
的complete
功能:
var n = Test.val;
===更新===
您的問題是“如何在原始類對象中獲取局部值?”。 我的答案向您展示了如何獲取靜態對象的字段。
如果需要共享庫 ,則應將結構更改為:
function Test() {
var self = this;
this.begin = function(v) {
this.val = v;
this.recieve();
}
this.complete = function(o) {
var n = this.val;
}
this.recieve = function() {
$.ajax({
url : "http://www.yahoo.com/", // Dummy
type: "POST",
dataType: "json",
complete: function(data) {
self.complete(data);
},
timeout: 1000,
});
}
}
現在,您可以創建兩個不同的對象:
var c2 = new Test2;
c2.begin(10);
var d2 = new Test2;
d2.begin(20);
在完整的處理程序中, this
不是Test
。 常見的解決方案是為其創建代理變量。
recieve : function(){
var proxy = this;
$.ajax({
url : "http://www.yahoo.com/", // Dummy
type: "POST",
dataType: "json",
complete: function(){
proxy.complete();
},
timeout: 1000,
});
},
或者(在這種情況下)簡單地complete
函數內部的Test.val
complete: function(o){
var n = Test.val;
},
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.