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

Verim
  • 1,065
  • 9
  • 17
  • 1
    Does this answer your question? [How to access the correct \`this\` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – VLAZ Mar 08 '21 at 07:14
  • 1
    Also relevant: [How does the “this” keyword work?](https://stackoverflow.com/q/3127429) – VLAZ Mar 08 '21 at 07:15
  • in the foo function have ```return Example.bar();``` instead of ```this``` – bloo Mar 08 '21 at 07:19

2 Answers2

2

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));
Naor Levi
  • 1,713
  • 1
  • 13
  • 27
  • I like your workaround but its not correct. In TypeScript the `this` in a static function refers to the **current** class (inheritance respecting) – Verim Mar 08 '21 at 07:35
  • @Verim "*TypeScript the this in a static function refers to the current class (inheritance respecting)*" incorrect. – VLAZ Mar 08 '21 at 07:42
  • @VLAZ do you have a source? All IDE and compiler are working like I descripe – Verim Mar 08 '21 at 07:59
  • 2
    @Verim is your very example not enough to prove the opposite? [Here is another example](https://tsplay.dev/Nal06w) that shows `this` is still resolved at call time. Moreover, you can just look at the generated JS code. At no point is `this` being bound. [See also](https://github.com/Microsoft/TypeScript/wiki/'this'-in-TypeScript) – VLAZ Mar 08 '21 at 08:06
-1

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

ru4ert
  • 998
  • 2
  • 14
  • 25