2

I am learning node.js

I have a class like this ->

 const client = require('prom-client');

class PrometheusController {
    constructor () {
        let counter = new client.Counter({ name: 'http_total_requests', namespace:"test", help: 'test' });
}

    get (fn) {
        this.counter.inc(); // Inc with 1
}

Node js complains that the counter is undefined.

I tried saving the this variable as the posts here recommend but that is not accessible either - javascript class variable scope in callback function

How do I access the constructors variables?

Illusionist
  • 5,204
  • 11
  • 46
  • 76

1 Answers1

6

You cannot. Variables declared inside the constructor can only be accessed from the constructor.

What you probably want to do is this:

constructor() {
    this.counter = new client.Counter(...);
}

Remember, ES6 Classes are merely syntactic sugar around constructor functions so the above code corresponds to this ES5 code:

function PrometheusController() {
    this.counter = new client.Counter(...);
}

which can be used like:

let controller = new PrometheusController();
// controller.counter can be used here
Sumner Evans
  • 8,951
  • 5
  • 30
  • 47