0

我與jquery .get功能工作時也可以訪問javascript對象變量無法通過從對象

我無法使用對象來訪問對象變量的JavaScript代碼低於

function cons1(x){ 
 

 
\t this.x = ++x || false; 
 
\t this.objectarray1 = []; 
 
\t 
 
\t if(this.x){ 
 
\t \t alert('x has value'); 
 
\t } 
 
} 
 
cons1.prototype.profun1 = function(){ 
 

 
\t alert(this.objectarray1[0]); 
 
\t 
 
\t $.get('requesting url',{'parameters'},function(data){ 
 

 
\t \t this.objectarray1[0] = this.x;// <-- can place a value 
 
    alert(this.objectarray1[0]);// <-- alerts this.x value 
 
\t }.bind(this)); 
 
} 
 

 
var x=1; 
 

 
var obj1 = new cons1(x); 
 
obj1.profun1(); 
 
var y = obj1.objectarray1[0]; 
 
alert(y);// <-- gives undefined on screen

+2

'變種Y = a1.objectarray1 [0];' - 哪裏'a1'突然來自? –

+0

請格式化您的代碼,但耶看起來像jaromanda發現你的問題 – Andrew

+0

順便說一句 - '$ .get'是異步的,所以即使你修復了這個錯字,你也會發現同樣的問題 - 你得到了'.objectarray1 [0]'在異步操作之前有機會添加任何東西到'.objectarray1 [0]' –

回答

0

原始代碼:

function cons1(x){ 
 

 
\t this.x = ++x || false; 
 
\t this.objectarray1 = []; 
 
\t 
 
\t if(this.x){ 
 
\t \t alert('x has value'); 
 
\t } 
 
} 
 
cons1.prototype.profun1 = function(){ 
 

 
\t alert(this.objectarray1[0]); 
 
\t 
 
\t $.get('requesting url',{'parameters'},function(data){ 
 

 
\t \t this.objectarray1[0] = this.x;// <-- can place a value 
 
    alert(this.objectarray1[0]);// <-- alerts this.x value 
 
\t }.bind(this)); 
 
} 
 

 
var x=1; 
 

 
var obj1 = new cons1(x); 
 
obj1.profun1(); 
 
var y = obj1.objectarray1[0]; 
 
alert(y);// <-- gives undefined on screen

轉換爲:

function cons1(x){ 
 

 
\t this.x = ++x || false; 
 
\t this.objectarray1 = []; 
 
\t 
 
\t if(this.x){ 
 
\t \t alert('x has value'); 
 
\t } 
 
} 
 
cons1.prototype.profun1 = function(){ 
 

 
\t alert(this.objectarray1[0]); 
 
\t 
 
    $.ajax({// <-- converted to ajax run sync 
 
    url:'requesting url', 
 
    data:{'parameters'}, 
 
    async : false, 
 
    success:function(data){ 
 
\t \t this.objectarray1[0] = this.x;// <-- can place a value 
 
     alert(this.objectarray1[0]);// <-- alerts this.x value 
 
\t }.bind(this) 
 
    }); 
 
} 
 

 
var x=1; 
 

 
var obj1 = new cons1(x); 
 
obj1.profun1(); 
 
var y = obj1.objectarray1[0]; 
 
alert(y);// <-- now gives value