Get array in other method in the same class in javascript

Niels Van Steen :

I have been looking for an answer on here but i couldn't find any, but anyway my question is how to get an array in a method that has been declared and initialised in an other method but in the same class. I'll make it a bit more clear by demonstrating what i want to achieve and what i have tried so far.

Javascript:

class SomeClass {
   method1() {
      var array = new array();
      //its actually a 2d array and it is being initialised here but for simplicity this isn't 
      //necessary in the example.
   }

   method2() {
   // --> Here i want to access the array and it's contents.

   //I have tried this:
   this.array;
   //and 
   array;
   }
}

but i got "cannot ready property of undefined" when i tried this.array;

John :

You have to declare the array as an element of the Class, not inside a method, for that, you can use a constructor.

In this link you can see more information.

Here is an example:

class SomeClass {
  constructor(someValue) {
    // Initialize array or any other atribute
    this.arr = new Array(someValue);
  }
  
   method1() {
      console.log(this.arr);
   }

   method2() {
     console.log(this.arr);
   }
}

var instance = new SomeClass('data');
instance.method1();
instance.method2();

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=31886&siteId=1