Why do we use the type "Static" in a function in Typescript?

Asked

Viewed 216 times

3

Why do we use the word static in a function in Typescript/Angular?

Is she a type or just a reserved word? How can we refer to her?

Example:

export class ClasseExemplo{
    static fazerAcaoComponent() {}
}

It is possible to use the static in classes as well?

1 answer

2


He’s an access modifier, not a type, in this case the method is without type. More generally we can say that it is an attribute of the member of a class, in this specific case of a class method.

The static defines that this method is static, so it behaves as a function in the class scope. It differs from a "normal" method that is instance, so the normal method operates over object (in fact even if you don’t see it takes an extra parameter called this to operate on the object). The static method does not receive any extra parameter, it can only operate in the class itself, it cannot directly access data from any object (unless you pass it, which is not the case with this method that has no parameters) so in this example or it does something without relying on anything external, or it would have in the class a static field that it can access.

This example in this way does not make much sense because a function would do the same (of course, the fact that neither have implementation would be better or have nothing. Of course within a class creates a scope and outside the function would be global.

static cannot be used in classes as in other languages, but the same effect can be obtained by creating a module.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.