0

Hi guys I'm a newbie in JS and I'd like to know how to call an array of a different class inside another function that belongs to the same javascript class. Here is the sample code:

class Something {

  constructor () {}

  async functionA () {
       this.list = []
  }

  async functionB () {
       console.log(this.list)
  }

}
Drun
  • 529
  • 1
  • 7
  • 17
  • You cannot call an array, you can only call a function. And what do you mean by "different class", there is only one in the code you've shown? – Bergi Dec 16 '19 at 00:52
  • So `var thing = new Something(); thing.functionA(); thing.functionB();`? That should do what you want. – Bergi Dec 16 '19 at 00:53

2 Answers2

0

In the constructor you can declare your variables with this.variableName and then other class methods will be able to get and set the value. You can also access it from an instance of the class.

class Something {

    constructor() {
        this.list = []
    }

    async functionA () {
        this.list = [ 'foo', 'bar']
    }

    async functionB () {
        console.log(this.list)
    }

}
Michael Rodriguez
  • 2,142
  • 1
  • 9
  • 15
0

What you're doing seems to work fine...

class Something {
  constructor () {}

  async functionA () {
    this.list = ['ok']
  }

  async functionB () {
    console.log(this.list)
  }
}

const a = new Something();
a.functionA();
a.functionB();

https://codepen.io/benaloney/pen/dyPpELK

Ben Winding
  • 10,208
  • 4
  • 80
  • 67