Reputation: 1125
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
Reputation: 1179
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
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