我正在使用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 。这怎么了请帮助澄清疑问。