javaScript对象无法访问对象变量

时间:2017-05-30 05:17:39

标签: javascript jquery javascript-objects google-api-js-client

我正在使用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

1 个答案:

答案 0 :(得分:0)

原始代码:

&#13;
&#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]);
	
	$.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;
&#13;
&#13;

转换为:

&#13;
&#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;
&#13;
&#13;