Typescript类-私有和受保护的属性可见

时间:2019-06-03 11:09:32

标签: typescript

我正在使用TypeScript 3.4.5,并且像下面这样声明了一个 Person 类,并创建了其实例 person

class Person {
    name: string;
    private personType: string = "Awesome Guy";
    protected age: number = 27;

    constructor(name: string, public userName: string) {
        this.name = name;
    }
}

const person = new Person("John", "john");
console.log(person); // {"userName":"john","personType":"Awesome Guy","age":27,"name":"John"}

但是,当我打印 person 对象的值时,它也显示了 private protected 成员的值。我什至可以访问它们,例如 person.personType person.age (尽管编译器会出错),但它会打印正确的值,而不是 undefined 。这怎么了请帮助澄清疑问。

0 个答案:

没有答案