本文内容如下
class类
如果你都有了答案,可以忽略本文章,或去TS学习地图寻找更多答案
ES6中的 TS类
公共属性修饰符:
- public:公开的,可读可写,默认修饰符
- private:私有的,不可读不可写
- protected:子类可访问
- readonly: 只能读不能写
- static:静态属性或静态方法(JS中也有)
class Animal {
public name: string;
constructor(name: string){
this.name = name
}
static isAnimal(instantce) {
return instantce instanceof Animal
}
eat(){
console.log(`${this.name} is eating`)
}
}
const dog = new Animal('旺财')
dog.eat()
Animal.isAnimal(dog)
TS类继承
class Person {
name: string
constructor(name: string) {
this.name = name
}
run(): string {
return `${this.name} is running`
}
}
let p = new Person('dashen')
p.run()
class Student extends Person {
constructor(name: string, public age: number) {
super(name)
}
study() {
console.log(`${this.name} is studying`)
}
}
const s = new Student('小明')
console.log(s)
s.study()
存取器 setter getter
例子:对名字的长度做出限制
class People {
private _fullname: string = 'tom'
get fullname(): string {
return this._fullname
}
set fullname(name: string) {
if (name && name.length < 6) {
this._fullname = name
} else {
console.log(`the length of '${name}' is greater than 6`)
}
}
}
let p = new People()
console.log(p.fullname);
p.fullname = 'hello world'
p.fullname = 'hello'
console.log(p.fullname);
抽象类
抽象类:原型
- 使用关键字:abstract,抽象方法只能出现在抽象类里面
- 提供其他类继承的基类,不能直接被实例化
- 抽象类的子类必须实现抽象类里面的抽象方法
abstract class Animal {
name: string = ''
contructor(name: string) {
this.name = name
}
run() {
console.log(this.name + 'is running')
}
abstract eat(): any
}
class Dog extends Animal {
constructor(public name: string) {
super()
}
eat() {
console.log(this.name + 'is eating')
}
sleep() {
console.log(this.name + 'is sleeping')
}
}
let d: Dog = new Dog('旺财')
d.eat()
d.run()
let d = new Animal('旺财')
let d: Animal = new Dog('旺财')
d.sleep()
学习更多
TS学习地图
|