Search code examples
typescriptangularangular2-templateangular2-directives

Why am I able to access private member of the class?


My code is as follow

@Component({
  selector: 'my-app',
  template: `
    <ul>
    <li *ngFor = 'let hero1 of heros2'>
    {{hero1.name}}
    </li>
    </ul>        
 `})

export class AppComponent {   
heros2 : any = [
    new heross('lee', 'lee'),
    new heross('lee1', 'lee1'),
];}

class heross{
 private name : string;
 constructor(name : string, details : string){
     this.name = name; 
}}
bootstrap(AppComponent);

why am I able to access name in the view and displaying name, provided that I have given it private keyword


Solution

  • If you'll try:

    class A {
        private x: number;
    }
    
    let a = new A();
    console.log(a.x);
    

    (code in playground)

    You'll get a compilation error:

    Property 'x' is private and only accessible within class 'A'

    The reason you're not getting that, I suspect (as I'm not an angular developer), is that you're having hero1.name in a string so the typescript compiler doesn't treat hero1 as a variable.

    I bet that if you try:

    let obj = new heross("name", "details");
    console.log(`heross.name: ${ obj.name }`);
    

    Then you'll get the compilation error.
    The difference being ${} instead of {{}}.

    If however you're asking why that's accessible at runtime, then that's because there's no notion of visibility in javascript, it doesn't get pass the compiler.


    Edit

    There's a difference between the angular double curly brace ({{ }}):

    The double curly brace notation {{ }} to bind expressions to elements is built-in Angular markup

    Which you don't need to put into ticks, you can just use regular single/double quotes.

    And the javascript template literals (${ }):

    Template literals are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them. They were called "template strings" in prior editions of the ES2015 / ES6 specification

    More simply:

    let x = 4;
    console.log(`x={{ x }}`); // outputs 'x={{ x }}'
    console.log(`x=${ x }`); // outputs 'x=4'