0

I'm working with jquery .get function

I'm unable to access the object variables using object the javascript code is below

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
  • 2
    `var y = a1.objectarray1[0];` - where did `a1` suddenly come from? – Jaromanda X May 30 '17 at 05:19
  • please format your code, but yeah looks like jaromanda found your problem – Andrew May 30 '17 at 05:20
  • by the way - `$.get` is asynchronous, so even when you fix that typo, you'll find the same problem - you're getting `.objectarray1[0]` before the asynchronous operation has had a chance to add anything to `.objectarray1[0]` – Jaromanda X May 30 '17 at 05:21
  • I think u meant `var y = obj1.objectarray1[0]` This should be done once ur request is resolved – sanket May 30 '17 at 05:21
  • nah @Andrew, that would produce a different error - something about a1 not defined most likely - I think that typo isn't the issue at all - it's not knowing how to work with asynchronous code that is the issue – Jaromanda X May 30 '17 at 05:22
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Andreas May 30 '17 at 05:26

1 Answers1

0

Original code:

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

Converted to :

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