为什么我可以访问班级的私人成员? [英] Why am I able to access private member of the class?
问题描述
我的代码如下
@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
推荐答案
如果您尝试尝试:
class A {
private x: number;
}
let a = new A();
console.log(a.x);
You'll get a compilation error:
属性"x"是私有的,只能在类"A"内访问
Property 'x' is private and only accessible within class 'A'
我怀疑(因为我不是有角度的开发人员)而未得到此命令的原因是,您在字符串中包含了hero1.name
,因此打字稿编译器不会将hero1
视为变量.
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 {{}}
.
但是,如果您要问为什么在运行时可以访问它,那是因为javascript中没有可见性的概念,它无法通过编译器.
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.
双花括号({{ }}
)之间是有区别的:
There's a difference between the angular double curly brace ({{ }}
):
用于将表达式绑定到元素的双大括号符号{{}} 是内置的Angular标记
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.
和 javascript模板文字(${ }
) :
模板文字是允许嵌入表达式的字符串文字. 您可以将多行字符串和字符串插值功能与 他们.在以前的版本中,它们被称为模板字符串" ES2015/ES6规范
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
更简单:
let x = 4;
console.log(`x={{ x }}`); // outputs 'x={{ x }}'
console.log(`x=${ x }`); // outputs 'x=4'
这篇关于为什么我可以访问班级的私人成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!