Verim
Verim

Reputation: 1125

"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?

Upvotes: 4

Views: 1161

Answers (2)

ru4ert
ru4ert

Reputation: 1179

Working Example

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

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

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

    console.log(Example.foo()); // works
    console.log(Broken.breaksThis(Example.foo)); 

Upvotes: -1

Naor Levi
Naor Levi

Reputation: 1813

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));

Upvotes: 3

Related Questions