Alex
Alex

Reputation: 1

Calling a certain variable from a method in JavaScript

I would like to know how I can write a method in such a way that I can later call a variable stored in it.

Of course, after I export and import into another Javascript file, I want to call the variable from the method, but I don't know exactly the syntax and if I have to use 'this'

I also don't know what to return to have all the declared variables available at any time

I want something like

class Security {
  chooseEntrance(FrontEntrance, BackEntrance) {
    FrontEntrance = //some code//
    BackEntrance = //some code//
  }
}

export default Security

And from another file, after import, call something like Security.chooseEntrance(FrontEntrance)

I hope I've set out all the data I need

Upvotes: 0

Views: 66

Answers (2)

Chili
Chili

Reputation: 154

You can't do that. By typing Security.chooseEntrance(FrontEntrance) you ask to execute the function and not get the variable in the function. We need more context to answer you propely but an answer can be either to store the variable somewhere in the script wich call the function or to create a field in the class Security and retrieve it later with a getter like this:

class Security{
    frontEntrance

    getFrontEntrance(){
        return frontEntrance
    }

    chooseEntrance(FrontEntrance,BackEntrance){
      FrontEntrance=//some code//
      BackEntrance=//some code//
    }

  }
export default Security

Upvotes: 1

Ashiq Hassan
Ashiq Hassan

Reputation: 428

class Security {
  FrontEntrance;
  BackEntrance;
  chooseEntrance(FrontEntrance, BackEntrance) {
    this.FrontEntrance = FrontEntrance;
    this.BackEntrance = BackEntrance;
  }
}

export default Security;

from some other class you access

const security = new Security();
security.chooseEntrance('', '');


security.FrontEntrance;
security.BackEntrance;

Upvotes: 0

Related Questions