What are the practical differences between a static class method, and a function defined outside a class (at the top of the file) in TypeScript?
I know that there are differences regarding visibilty from other classes and files. When visibility is not a concern though (the function/method is only used in one class), when should we use static methods rather than functions defined outside any classes.
Example:
export class Foo {
constructor(bar: string) {
Foo.shout(bar);
}
private static shout(content: string) {
console.log(string.toUpperCase());
}
}
VS
export class Foo {
constructor(bar: string) {
shout(bar);
}
}
function shout(content: string) {
console.log(string.toUpperCase());
}
What are the practical differences between a static class method, and a function defined outside a class (at the top of the file) in TypeScript?
Not all that many:
Code using the static method must have access to the class; code using a standalone function must have access to the standalone function instead.
Using the static method technically involves a property lookup on the class's constructor function; using a standalone function doesn't. In practice, this will be optimized such that it doesn't matter.
The code in the static method will have access to the constructor function's parent constructor function via super (something that's fairly unique to JavaScript); code in a standalone function does not (because there is no parent constructor).
Specifically in regard to your example: Your standalone shout function is private to the module in which it appears; the static method on Foo is accessible from other modules that import Foo.
Slightly closer to opinion-land:
import provides some context for the standalone function....when should we use static methods rather than functions defined outside any classes.
That's largely a matter of opinion and style, so off-topic for Stack Overflow. If your team feels the need for consistency using some set of rules, agree a set and be consistent.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With