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?

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.