Website-Suche

typescript - „this ist in statischer Funktion undefiniert“


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"

Ein interaktives Beispiel finden Sie hier.

Ich möchte verstehen, warum das erste Log wie beabsichtigt funktioniert, das zweite jedoch fehlschlägt. Und wie könnte ich es beheben?

Antwort #1

Sie missbrauchen this in einer statischen Methode einer Klasse.
Versuchen Sie dies, um es zu beheben:

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

Antwort #2

Funktionierendes Beispiel

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

Verwandte Artikel