Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"this is undefined" in static function

class Example{
    static foo():string{
        return this.bar();
    }

    static bar():string{
        return "bar";
    }
}

class Broken{
    static breaksThis(callback: () => string):string{
        return callback();
    }
}

console.log(Example.foo()); // works
console.log(Broken.breaksThis(Example.foo)); // Error at line 3: "this is undefined"

An interactive Example can be found here.

I would like to understand why the first log works as intended but the second fails. And how could I fix it?

like image 919
Verim Avatar asked Oct 14 '25 16:10

Verim


1 Answers

You are abusing this in a static method of a class.
Try this in order to fix:

class Example {
    static foo(): string {
        return Example.bar(); /* Here is the fix */
    }

    static bar(): string {
        return "bar";
    }
}

class Broken {
    static breaksThis(callback: () => string): string {
        return callback();
    }
}

console.log(Example.foo()); // works
console.log(Broken.breaksThis(Example.foo));
like image 137
Naor Levi Avatar answered Oct 17 '25 10:10

Naor Levi



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!