问题
Recently come across the following conundrum:
Standards
The Typescript documentation suggests creating object definitions with private members having an underscore prefix, allowing getters/setters to utilize the original 'name' of said members, providing indirect public access (as they should).
The Angular documentation recommends otherwise, however does not provide an example of using getters & setters for the private variable in their object definition example.
The Issue
I've been following the Typescript coding standard to the most extent. Take the following class for example:
public class Foo{
private _bar:string;
constructor(){ this._bar='Baz'; }
get bar():string{return this._bar}
}
Using the following code to serialize it into JSON:
console.log(JSON.stringify(new Foo()));
...will produce:
{
'_bar': 'Baz'
}
Questions
- Taking into account these are 'guidelines' and simply recommendations, what would be the Angular-way of handling an object definition, allowing for direct serialization?
- In my example, surely the private access modifier shouldn't allow direct access to the value of it? What have I missed in my understanding of using the private access modifier here?
I've done a fair share of reading to other articles and StackOverflow posts regarding different ways of handling serialization, want to deter from the 'how', and rather ask 'why' with regards to the behavior mentioned.
Any feedback would be greatly appreciated! :)
Kind regards
回答1:
You can customize serialization by implementing toJSON()
public class Foo{
private _bar:string;
constructor(){ this._bar='Baz'; }
get bar():string{return this._bar}
toJSON() {
return {bar: _bar};
}
static fromJSON(json) {
...
}
}
See also http://choly.ca/post/typescript-json/
Getters and setters are pure TypeScript language feature and entirely unrelated to Angular.
private
is only for static analysis in TypeScript. When it's transpiled to JS private
won't exist anymore. It becomes a plain old JS object and JSON.stringify
treats it like that.
来源:https://stackoverflow.com/questions/44407491/angular-2-or-4-object-serialization