I am building an app using babel preset ES2015.
class Foo {
bar(arg) {
console.log(arg)
}
baz(arg) {
this.bar(arg)
}
}
function callBaz(callback) {
callback("hello, wolrd")
}
instance = new Foo()
callBaz(instance.baz)
// Uncaught TypeError: Cannot read property 'bar' of undefined
I'd like to be able to pass a reference to baz
in the context of Foo instance.
Two options for that:
Options 1:
class Foo {
bar(arg) {
console.log(arg)
}
baz() {
let self = this
return(function(callback) {
self.bar(callback)
}
}
}
function callBaz(baz) {
baz("hello, wolrd")
}
instance = new Foo()
callBaz(instance.baz())
// hello, world
Options 2:
class Foo {
bar(arg) {
console.log(arg)
}
baz(arg) {
this.bar(arg);
}
}
function callBaz(callback) {
callback("hello, wolrd")
}
instance = new Foo()
var baz = instance.baz.bind(instance)
callBaz(baz)
// hello, world
Basically I don't like any of those solution and I am looking for another way to inject the context of the instance together with the callback method.
I could imagine doing something like this by either:
- Using some native javascript paradigm/syntax (ES2015, 2016?) which I am familiar with
- Using any Babel transform plugin ?
- Adding an intermediate layer on the parent Foo class ?
- Using any third-party library helping with that ?
Of course my problem isn't really one, since it's due to the nature of Javascript it-self, but I am wondering if there would be any "seamless" alternative or syntax to proceed with the binding.
NB: bar
and baz
could be static
, but as far as I see the problem the same
Thanks !