The code below prints out Value: undefined because (I assume) the scope of the console.log() statement is ExternalLibrary where there is no x defined. So how so I resolve the issue? I'm guessing there is a solution using closures but cannot figure out what it is.
class ExternalLibrary {
callback
setup(callback) {
this.callback = callback
}
call() { this.callback() }
}
class Main {
x = 1
doIt() {
const lib = new ExternalLibrary()
lib.setup(function () {
console.log('Value: ' + this.x)
})
lib.call()
}
}
new Main().doIt()