A
A
Azamat_TURBO2020-04-16 21:13:11
JavaScript
Azamat_TURBO, 2020-04-16 21:13:11

How to access variables of one class from another class?

I suspect (strongly) that I don't understand classes very well.

Suppose there is such a program.
https://codepen.io/Azamat_TURBO/pen/jObqMrx?editor... The

question is: how can I reach importantVar from the SecondClass class, which is in the FirstClass?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
Tigran Abrahamyan, 2020-04-16
@Azamat_TURBO

that I don't understand the classes very well

You obviously need to inherit here, read about extends .
class FirstClass {
  constructor() {
    this.importantVar = '1234asd'
  }
  
  someFunction() {
    alert(this.importantVar);
  }
}

class SecondClass extends FirstClass {
  constructor(importantVar) {
    super();
    this.justAnotherVar = 'ooooo';
  }

  iWannaImportantVar() {
    alert(this.importantVar);
  }
}

function gasgasgas() {
  const firstClass = new FirstClass();
  const secondClass = new SecondClass();

  firstClass.someFunction();
  secondClass.iWannaImportantVar();
}

gasgasgas();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question