为什么我可以访问类的私有成员? [英] Why am I able to access private member of the class?

查看:38
本文介绍了为什么我可以访问类的私有成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码如下

@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'

我怀疑(因为我不是 Angular 开发人员),你没有得到它的原因是你在一个字符串中有 hero1.name 所以打字稿编译器没有t 将 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.

角度双花括号 ({{ }}):

双花括号符号 {{ }} 将表达式绑定到元素是内置的 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屋!

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