- ts 可以使用访问控制符来保护对类、变量、方法和构造方法的访问
- ts 支持 3 种不同的访问权限
**public**
- 公有
- 可以在任何地方被访问
- public 是默认值
**protected**
- 受保护
- 可以被其自身以及其子类访问
**private**
- 私有
- 只能被其定义所在的类访问
class Encapsulate { str1: string = "hello" // public 是默认值,上述写法和下面这种写法等效 // public str1: string = "hello" private str2: string = "world"}var obj = new Encapsulate()console.log(obj.str1) // 可访问console.log(obj.str2) // 编译错误, str2 是私有的// 报错:属性“str2”为私有属性,只能在类“Encapsulate”中访问。ts(2341)
- 类可以实现接口,使用关键字
implements
// 定义一个接口interface IPerson { firstName: string; lastName: string; sayHello(): string;}// 创建一个类来实现这个接口class Person implements IPerson { firstName: string; lastName: string; constructor(firstName: string, lastName: string) { this.firstName = firstName; this.lastName = lastName; } // 实现接口中的方法 sayHello(): string { return `Hello, my name is ${this.firstName} ${this.lastName}`; }}// 使用这个类const person = new Person("John", "Doe");console.log(person.sayHello());// Hello, my name is John Doe