示例代码:
//定义类
class Person {constructor () {}run () {}
}
在TypeScript是不允许直接在constructor 定义变量的 需要在constructor上面先声明 如果了定义了变量不用 也会报错 通常是给个默认值 或者 进行赋值
class Person {name:stringage:number = 0bol:booleanconstructor(name:string, age: number, bol: boolean) {this.name = name// this.age = agethis.bol = bol}
}new Person('zs', 18 , false)
public 修饰符 可以让你定义的变量 内部访问 也可以外部访问 如果不写默认就是public
private 修饰符 代表定义的变量私有的只能在内部访问 不能在外部访问
protected 修饰符 代表定义的变量私有的只能在内部和继承的子类中访问 不能在外部访问
static 定义的属性 不可以通过this 去访问 只能通过类名去调用
static 静态函数 同样也是不能通过this 去调用 也是通过类名去调用
class Person1 {public name:string //使用public 修饰符 可以让你定义的变量 内部访问 也可以外部访问 如果不写默认就是publicprivate age:number // 使用 private 修饰符 代表定义的变量私有的只能在内部访问 不能在外部访问protected bol:boolean //使用 protected 修饰 符 代表定义的变量私有的只能在内部和继承的子类中访问 不能在外部访问static aaa:string = '123456' // 静态属性 我们用static 定义的属性 不可以通过this 去访问 只能通过类名去调用 (Person1.aaa)constructor(name:string, age: number, bol: boolean) {this.name = namethis.age = agethis.bol = bol}// static 静态函数 同样也是不能通过this 去调用 也是通过类名去调用static run () {this.aaareturn this.aaa1()}static aaa1() {return 'skjdfbnoidfb'}}new Person1('zs', 18 , false)console.log(Person1.run())
interface 定义类 使用关键字 implements 后面跟interface的名字多个用逗号隔开 继承还是用extends
interface PersonClass {get(type: boolean): boolean
}interface PersonClass2{set():void,asd:string
}class A {name: stringconstructor() {this.name = "123"}
}class Person extends A implements PersonClass,PersonClass2 {asd: stringconstructor() {super()this.asd = '123'}get(type:boolean) {return type}set () {}
}
我们在A类定义了 getName 抽象方法但为实现
我们B类实现了A定义的抽象方法 如不实现就不报错 我们定义的抽象方法必须在派生类实现
abstract class N {name:stringconstructor(name:string) {this.name = name}setName(name:string) {this.name = name}abstract getName():string}class M extends N {constructor() {super('zs')}getName():string {return this.name}
}let q = new M()
q.setName('zs1')
q.getName()