我正在使用jquery .get
函数
我无法使用javascript代码低于
的对象访问对象变量
function cons1(x){
this.x = ++x || false;
this.objectarray1 = [];
if(this.x){
alert('x has value');
}
}
cons1.prototype.profun1 = function(){
alert(this.objectarray1[0]);
$.get('requesting url',{'parameters'},function(data){
this.objectarray1[0] = this.x;// <-- can place a value
alert(this.objectarray1[0]);// <-- alerts this.x value
}.bind(this));
}
var x=1;
var obj1 = new cons1(x);
obj1.profun1();
var y = obj1.objectarray1[0];
alert(y);// <-- gives undefined on screen
答案 0 :(得分:0)
原始代码:
function cons1(x){
this.x = ++x || false;
this.objectarray1 = [];
if(this.x){
alert('x has value');
}
}
cons1.prototype.profun1 = function(){
alert(this.objectarray1[0]);
$.get('requesting url',{'parameters'},function(data){
this.objectarray1[0] = this.x;// <-- can place a value
alert(this.objectarray1[0]);// <-- alerts this.x value
}.bind(this));
}
var x=1;
var obj1 = new cons1(x);
obj1.profun1();
var y = obj1.objectarray1[0];
alert(y);// <-- gives undefined on screen
&#13;
转换为:
function cons1(x){
this.x = ++x || false;
this.objectarray1 = [];
if(this.x){
alert('x has value');
}
}
cons1.prototype.profun1 = function(){
alert(this.objectarray1[0]);
$.ajax({// <-- converted to ajax run sync
url:'requesting url',
data:{'parameters'},
async : false,
success:function(data){
this.objectarray1[0] = this.x;// <-- can place a value
alert(this.objectarray1[0]);// <-- alerts this.x value
}.bind(this)
});
}
var x=1;
var obj1 = new cons1(x);
obj1.profun1();
var y = obj1.objectarray1[0];
alert(y);// <-- now gives value
&#13;