0

i am sending an int array from my android application and it's recieved very well in the JS but the thing is i'm assigning the array to a global variable but the variable is always undefined.

var values;
    function getFromAndroid() {

        alert(Android.getFromAndroid());
        this.values = Android.getFromAndroid();
        this.values = JSON.parse(this.values);
        alert("Hello! Data are: " + this.values + "; first = " + this.values[0]); //not null

        }

        var chart;
    alert("Hello!: " +this.values[0]); //undefined
Hussein Yassine
  • 53
  • 1
  • 1
  • 6
  • 2
    Since you don't call the function, values is never initialized – AxelH Jul 08 '16 at 08:19
  • I'm calling it onLoad() – Hussein Yassine Jul 08 '16 at 08:21
  • You're trying to use `values` *before* it's filled in asynchronously. See the linked question and its answers. Short version: Trigger your code using it from within `getFromAndroid`. – T.J. Crowder Jul 08 '16 at 08:22
  • onLoad, but where is this code snippet ? Outside the onLoad, so the alert is called before. If you load you page and run the alert in the console, this will probably work. – AxelH Jul 08 '16 at 08:25
  • 1
    In javascript this keyword will assign to local function variable. Check [This](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/this) link. this keyword will act differently in javascript than other languages. – Shubham Jul 08 '16 at 08:25

1 Answers1

0

this keyword acts differently in javascript than other languages. It'll reffer to local variable not the global variable .This code snippet will clear your doubts i guess.

var globalVar ;

function a() {
  this.globalVar = 30;
  globalVar = 40;
}

var obj = new a();

console.log(obj.globalVar + "\t" + globalVar);
Shubham
  • 1,755
  • 3
  • 17
  • 33