class A {
constructor() {
this.a = ""
}
run() {
b.on("event", function(data) {
// how to access variable a here?
})
}
}
how to access a class variable inside a closure?
class A {
constructor() {
this.a = ""
}
run() {
b.on("event", function(data) {
// how to access variable a here?
})
}
}
how to access a class variable inside a closure?
You can use an arrow function, this will preserve the reference to 'this' of run()
inside the callback
const { EventEmitter } = require("events");
const b = new EventEmitter()
class A {
constructor() {
this.a = "hello i am a"
}
run() {
b.on("event", (data) => {
console.log(this.a)
})
}
}
const classA = new A();
classA.run()
b.emit("event");