Share variables between methods within the same class

I have a project in Node JS and Typescript in which I have a class with two methods. Both methods use the same variable that I pass from another class in a different file. Is there a way to pass the variable to the class only once to use it in the methods without repeating it?

This is my class:

export class jsonUtils extends constUtils {

    jsonUrl(api: any) {
        const url = this.conf.API_MOCS[`${api}`].url;
        return url;
    }

    fileName(api: any){
        const nameFile = `${this.env}.${api}`;
        return nameFile;
    }

}

This is the call I make from the other file:

let nameFile = new jsonUtils().fileName(api);

Something like this is what I would like to achieve, to have a variable in the class that I can call from all the methods:

export class jsonUtils extends constUtils {

    let api = 'api';

    jsonUrl() {
        const url = this.conf.API_MOCS[`${api}`].url;
        return url;
    }

    fileName(){
        const nameFile = `${this.env}.${api}`;
        return nameFile;
    }

}

1 answer

  • answered 2021-06-10 11:02 Felix Dolderer

    Create a constructor for your class that takes your "api"-argument and stores it in a class-wide variable.

    Or if a constructor is not viable, create a separate setApi() function.