简体   繁体   中英

private members are accessible in angular 2 decorators

Consider this code:

export class Hero {
    constructor(private id: number, private name: string) {}
}

@Component({
    selector: 'my-app',
    template: '<h1>{{title}}</h1><h2>{{hero.name}} details!</h2>'
})
export class AppComponent {
    private title = "Tour of Heroes";
    private hero: Hero = new Hero(1, "Windstorm");
}

In AppComponent 's template I wrote hero.name , however, this field is private according to the Hero class and should not be accessible. How this code compiles and works? am I missing something?

EDIT: Read the answers on why it happens, here's my way of handling this, it's not a fix but it keeps things more organized and safe , besides accessors are always good to use:

export class Hero {
    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>{{hero.name}} details!</h2>'
})
export class AppComponent {
    private title = "Tour of Heroes";
    private hero: Hero = new Hero(1, "Windstorm");
}

When hero.name will be executed in JS it should call the JS-compiled getter function you defined in your TS code, this should give some sort of control over the properties while maintaining TS code-style.

In JavaScript there is no such thing as private variables. Keywords like private are just used by the TypeScript transpiler to enforce constraints before transpilation. Once the code is transpiled into JavasScript, the name property is a visible member of the Hero class.

The private keyword in typescript is just used for compile time checking and doesn't actually restrict access to anything at runtime. The typescript compiler isn't checking your templates so it's not catching the issue.

I believe some IDE's (VS Code and WebStorm) are working on type checking your templates but for now you are on your own

Angular2 states referring private variables within templates as a correct way. See cheat-sheet: https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#parent-to-child-setter .

So go ahead! And enable encapsulation to your components not exposing every variables as public.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM