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

允我心安 提交于 2019-12-25 06:23:53

问题


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


回答1:


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'



回答2:


Privacy is not enforced in TypeScript in general but only checked by static tools.

You can see the bindings in the view and the component class as a single unit, like the bindings in the template is part of the class implementation.

With the offline template compiler I assume this is actually how the generated code will be organized.




回答3:


Because it's javascript at the end of the day. And Javascript language does not have a private keyword.



来源:https://stackoverflow.com/questions/37997251/why-am-i-able-to-access-private-member-of-the-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!