ts里的三种修饰符
1、public:公有,在类里面、子类、类外面都可以访问
2、protected:保护类型,在雷里面、子类里面可以访问,在类外部不能访问
3、private:私有,在类里面可以访问,子类、类外边不能访问
属性如果不加修饰符默认是公有(public)
class Person{
name:string //公有属性
constructor(name:string){
this.name=name
}
run():string{
return `${this.name}在运动`
}
}
class Web extends Person{
constructor(name:string){
super(name);
}
run():string{
return `${this.name}在运动-子类`
}
work(){
alert(`${this.name}在工作`)
}
}
var w = new Web('李四');
w.work()
//公有属性外部获取
var p = new Person('哈哈哈')
alert(p.name)
//-------------ts静态类 静态方法
class Per{
public name:string;
public age:number=20;
//静态属性
static sex="男";
constructor(name:string){
this.name=name;
}
run(){
alert(`${this.name}在跑步`)
}
work(){
alert(`${this.name}在工作`)
}
static print(){
alert('print方法'+this.age)//静态方法,里面没法直接调用类里面的属性
alert('print方法'+Per.sex) alert('print方法'+Per.sex)//这个可以
}
}
Per.print();
alert(Per.sex);
//-------------ts中的抽象类:它是提供其他类继承的基类,不能直接被实例化
用abstract关键字定义抽象类和抽象方法,抽象类中的抽象方法不包含具体实现并且必须在派生类中实现
abstract抽象方法只能放在抽象类里
抽象类和抽象方法用来定义标准。例:animal这个类要求它的子类必须包含eat方法
abstract class Animal{
public name:string;
constructor(name:string){
this.name=name;
}
abstract eat():any;//抽象方法中不包含具体的实现
run(){
console.log("其他方法可以不实现")
}
}
var a = new Animal()//错误的写法
class Cat extends Animal{
//抽象类的子类必须实现抽象类里的抽象方法
constructor(name:any){
super(name)
}
run(){}
eat(){
console.log(this.name+'老鼠')
}
}
var c = new Cat('小花猫')
c.eat();

浙公网安备 33010602011771号