私人成员可使用angular 2装饰器访问 [英] private members are accessible in angular 2 decorators

查看:85
本文介绍了私人成员可使用angular 2装饰器访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码:

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");
}

AppComponent 的模板中,我编写了 hero.name ,但是,根据 Hero 类,此字段是私有的,不应设置为无障碍.该代码如何编译和工作?我错过了什么吗?

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?

编辑:请阅读有关其发生原因的答案,这是我的处理方式,它不是解决方案,但可以使事情井井有条,更安全 ,除了访问者还可以总是很好用:

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");
}

当将在JS中执行 hero.name 时,应调用您在TS代码中定义的JS编译的getter函数,这应在保持TS代码的同时对属性进行某种控制,样式.

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.

推荐答案

在JavaScript中,没有私有变量之类的东西.TypeScript编译器仅使用诸如 private 之类的关键字来在编译之前强制执行约束.将代码转换为JavasScript后, name 属性将成为Hero类的可见成员.

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.

这篇关于私人成员可使用angular 2装饰器访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆