为什么我能够访问班级的私人成员?

问题描述 投票:0回答:3

我的代码如下

@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);

为什么我能够在视图中访问名称并显示名称,前提是我已经给它私有关键字

typescript angular angular2-template angular2-directives
3个回答
2
投票

如果您尝试:

class A {
    private x: number;
}

let a = new A();
console.log(a.x);

(Qazxswpoi)

你会得到一个编译错误:

属性'x'是私有的,只能在'A'类中访问

我怀疑(因为我不是一个有角度的开发人员),你是因为你在一个字符串中有code in playground,所以typescript编译器不会将hero1.name视为一个变量。

我敢打赌,如果你尝试:

hero1

然后你会得到编译错误。 差异是let obj = new heross("name", "details"); console.log(`heross.name: ${ obj.name }`); 而不是${}

但是,如果你问为什么在运行时可以访问它,那就是因为javascript中没有可见性的概念,它不会通过编译器。


Edit

角度{{}}double curly brace)之间有区别:

用于将表达式绑定到元素的双花括号符号{{}}是内置的Angular标记

您不需要将其放入刻度线,您可以使用常规的单/双引号。

{{ }}javascript template literals):

模板文字是允许嵌入表达式的字符串文字。您可以使用多行字符串和字符串插值功能。它们在ES2015 / ES6规范的先前版本中被称为“模板字符串”

更简单:

${ }

1
投票

一般情况下,TypeScript中不会强制实施隐私,只能通过静态工具进行检查。

您可以将视图中的绑定和组件类视为一个单元,就像模板中的绑定是类实现的一部分一样。

使用离线模板编译器,我假设这实际上是如何组织生成的代码。


0
投票

因为它是一天结束时的javascript。并且Javascript语言没有let x = 4; console.log(`x={{ x }}`); // outputs 'x={{ x }}' console.log(`x=${ x }`); // outputs 'x=4' 关键字。

© www.soinside.com 2019 - 2024. All rights reserved.