I am learning NodeJS and i have a big problem.
Using ES6 and executing with node --harmony
this in my constructor tell me it from Magic {} whereas in bar() it from my Function.
I seek everywhere but i didn't find how to fix it.
#!/usr/local/bin/node --harmony
class Test {
constructor() {
var tab = []
tab.push(this.bar)
console.log(this) // Magic {}
tab[0]("hello")
// this.bar("world")
}
foo(str) {
return str
}
bar(str) {
console.log(this.foo(str)) // TypeError: this.foo is not a function
console.log(this) // [ [Function: bar] ]
}
}
new Test()
When you do tab.push(this.bar), it loses current context. You need to a) bind it: tab.push(this.bar.bind(this)) or b) pass context when calling: tab[0].call(this, "hello").
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With