Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Script nodeJS with this error

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()
like image 329
albttx Avatar asked Dec 02 '25 09:12

albttx


1 Answers

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

like image 94
MartinP Avatar answered Dec 03 '25 23:12

MartinP



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!