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
  • 45,728
  • 6
  • 46
  • 64
takayama
  • 41
  • 3

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,765
  • 1
  • 10
  • 28