TypeScript - 属性的修饰符
class Person { /** * TS 可以再属性前增加属性的修饰符 * public 修饰的属性可以再任意位置访问(修改)默认值 * private 私有属性,私有属性只能在类内部进行访问和修改 */ public title: string; // 不加前缀其实就是public private name: string; private age: number; // 可以将前缀写在此处 // constructor(public title: string, private name: string, private age: number) { constructor(title: string, name: string, age: number) { this.title = title; this.name = name; this.age = age; } // 可用get set方式来实现getName和setName getName() { return this.name } get _name() { return this.name } setName(val: string) { this.name = val } set _name(val: string) { this.name = val } getAge() { return this.age } setAge(val: number) { if (val >= 0) { this.age = val } } } const per = new Person('Front-end Developer', 'Alan', 11) console.log(per, 'per'); console.log(per.getName(), 'per.getName()'); console.log(per._name, 'per._name'); per.setName('Faye') console.log(per.getName(), 'per.getName()'); per._name = 'Alan Faye'; console.log(per._name, 'per._name'); per.setAge(-30); console.log(per.getAge(), 'per.getAge()') per.setAge(18); console.log(per.getAge(), 'per.getAge()')