Correct naming of properties in Angular2+

2019-09-13 23:50发布

问题:

I want to write this:

private _name:string;
public get name():string{
    return this._name;
}

But the Angular Style Guide advise against it: https://angular.io/styleguide#!#03-04

Am I thinking wrong? What should I use instead?

回答1:

What you're using is TypeScript standard. Since you can't name your variable name, because get name() will be compiled to whatever.name, you have to use the underscore.

Angular isn't any different there because it uses TypeScript itself. They just say you should use name if you don't have a specific getter or setter method for that property.

I don't know if your code is just an example but it wouldn't make sense since the property name simply would be public in the end anyway.