[英]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.