0
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?

Nick Parsons
  • 38,409
  • 6
  • 31
  • 57
takayama
  • 31
  • 2

1 Answers1

1

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");

Dan Starns
  • 3,637
  • 1
  • 9
  • 27