Why do we use a "get" before declaring a function in Angular?

Asked

Viewed 219 times

10

  • Why do we use a get before declaring a function in Angular or Javascript?
  • That’s an Angular practice?
get funcaoExemplo() {
    return this.exemplo.length === (this.exemplo2 + 1);
  }

2 answers

12


This has nothing to do with Angular, this can by chance use this, has to do with Javascript. This method uses a project pattern called getter (has the Setter also). In some languages this standard is adopted by the programmer and only he knows that that method has this purpose. In JS, like other languages, it has proper syntax for this and thus gives a better semantics indicating to the compiler that the method is a getter.

But not there, it allows the method call syntax to work as if it were an object field, so this getter works as a property itself.

The name of the example is bad and lacks context, but could do so:

console.log(objeto.funcaoExemplo);

I put in the Github for future reference.

Would result in true or false.

You can see more in What is the advantage of using getters/setters in Javascript classes?.

Obviously it works in Typescript too.

6

Why do we use a get before declaring a function in Angular or Javascript?

We use to associate the property of an object to a function. The function is called when the property is accessed.

That’s an Angular practice?

No, this is Javascript.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get

Example:

get funcaoExemplo() {
    return this.exemplo.length === (this.exemplo2 + 1);
}

Access

console.log(obj.funcaoExemplo);

Browser other questions tagged

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