通过AJAX分配和使用javascript对象属性
Assign and use javascript object property via AJAX
所以我有这个Javascript对象:
var obj = {
conn : null,
first : function(thisIdentity) {
"use strict";
$(document).on('click', thisIdentity, function(e) {
e.preventDefault();
$.ajax ({
url : some value,
// other parameters
success : function() {
this.conn = new Connection(data.user_id, "127.0.0.1:80");
}
});
},
second : function(thisIdentity) {
"use strict";
$(document).on('click', thisIdentity, function(e) {
e.preventDefault();
$.ajax ({
url : some value,
// other parameters
success : function() {
// using this.conn now results in UNDEFINED
}
});
}
};
现在,在第一个函数的AJAX调用中,值基本上被分配给了conn变量,但当我试图在第二个函数中使用相同的值时,它会声明this.con未定义。我只想知道如何为对象的属性赋值,并保留它以备将来使用?谢谢
在ajax成功回调中,this
引用的范围与原始对象不同。
将您的代码更改为:
var obj = {
conn : null,
first : function(thisIdentity) {
"use strict";
var mySelf = this;
$(document).on('click', thisIdentity, function(e) {
e.preventDefault();
$.ajax ({
url : some value,
// other parameters
success : function() {
mySelf.conn = new Connection(data.user_id, "127.0.0.1:80");
}
});
},
second : function(thisIdentity) {
"use strict";
var mySelf = this;
$(document).on('click', thisIdentity, function(e) {
e.preventDefault();
$.ajax ({
url : some value,
// other parameters
success : function() {
// now you can access the connection with mySelf.conn
}
});
}
};
语法本身是错误的。您正在创建一个变量或在对象文字中给出一个表达式。记住,这不是一个函数,但它应该是:
$.ajax ({
// computation and in success function
conn: new Connection(data.user_id, "127.0.0.1:80")
});
更新
当你给出这样一种定义方式时:
success : function() {
this.conn = new Connection(data.user_id, "127.0.0.1:80");
}
这里,this
对象指的是success
函数,而不是您的object
。阅读理解JavaScript中的作用域和上下文。现在您需要为this
创建一个代理变量并使用它:
first : function(thisIdentity) {
"use strict";
var myObj = this;
$(document).on('click', thisIdentity, function(e) {
e.preventDefault();
$.ajax ({
url : some value,
// other parameters
success : function() {
myObj.conn = new Connection(data.user_id, "127.0.0.1:80");
}
});
},
相关文章:
- Chrome开发工具(如何知道我在调用哪个javascript对象)
- 循环遍历以数组为值的Javascript对象
- 从ajax请求中获取javascript对象
- 如何从对象的原型方法访问JavaScript对象属性
- 将XML转换为普通的旧JavaScript对象
- 通过引用传递JavaScript对象
- javascript对象操作:根据指定条件选择属性
- Javascript对象类在单击时打开窗口进行颜色选择,并在更改时替换对象背景颜色
- 如何在异步函数中使用javascript对象
- 临时Javascript对象
- 如何在ASP中为用户控件添加Javascript对象网
- 使用数组向下搜索Javascript对象
- Rails将JavaScript对象存储到Model的有效方式
- JavaScript对象不是从原型链继承的
- 如何创建具有默认值的JavaScript对象字段?(AngularJS模型相关)
- SetInterval在javascript对象中表现怪异
- Javascript 对象和 this 关键字
- 如何在不知道关键字的情况下访问javascript对象值
- 在 JavaScript 对象中设置要使用的运算符的属性
- 如何搜索JavaScript对象并更改值