Take a look at this piece of code:
export class Character {
constructor(private id: number, private name: string) {}
}
@Component({
selector: 'my-app',
template: '<h1>{{title}}</h1><h2>{{character.name}} details!</h2>'
})
export class AppComponent {
private title = "Adventure with Characters";
private character: Character = new Character(1, "Elena");
}
In the AppComponent
's template, I accessed character.name
, even though it is marked as private in the Character
class and technically should not be accessible. How does this code compile and run successfully? Am I overlooking something?
UPDATE: After reading through the explanations provided, I came up with my approach to this issue. Although it doesn't fix the problem entirely, it enhances organization and adds an extra layer of security. Using accessors is always beneficial:
export class Character {
constructor(private _id: number, private _name: string) { }
get name(): string {
return this._name;
}
get id(): number {
return this._id;
}
}
@Component({
selector: 'my-app',
template: '<h1>{{title}}</h1><h2>{{character.name}} details!</h2>'
})
export class AppComponent {
private title = "Adventure with Characters";
private character: Character = new Character(1, "Elena");
}
By defining getter functions within the TypeScript code, calling character.name
in JavaScript should trigger the corresponding getter function, offering some control over the properties while adhering to TypeScript conventions.