我正在学习 node.js
我有这样一个类->
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 提示计数器未定义。
我尝试按照此处帖子的建议保存 this
变量,但这也无法访问 - javascript class variable scope in callback function
如何访问构造函数变量?
最佳答案
你不能。在 constructor
中声明的变量只能从构造函数中访问。
您可能想要做的是:
constructor() {
this.counter = new client.Counter(...);
}
记住,ES6 类只是构造函数的语法糖,所以上面的代码对应于这个 ES5 代码:
function PrometheusController() {
this.counter = new client.Counter(...);
}
可以这样使用:
let controller = new PrometheusController();
// controller.counter can be used here
关于javascript - 访问 Node 中的构造函数变量。 js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45219613/