类的公共修饰符 默认不写就是public
class Animal{
public name:string;
public constructor(name:string){
this.name = name;
}
public move(num:number){
console.log(num);
}
}
const dog = new Animal('dog');
console.log(dog.name);
类的私有修饰符 实例不能访问,类里面可以访问,继承的类也不能访问
class Animal {
private name:string;
constructor(name:string){
this.name = name;
}
getName(){
console.log(this.name);
}
}
class Person extends Animal{
constructor(name){
super(name)
}
getName2(){
//这里不能访问,因为是name是private
console.log(this.name);
}
}
const cat = new Animal('cat');
cat.getName() //cat
cat.name //报错不能访问
类的保护修饰符,实例不能直接访问,类内核子类都能访问
class Animal {
protected name:string;
constructor(name:string){
this.name = name;
}
getName(){
console.log(this.name);
}
}
构造函数使用保护修饰符
class Person {
name:string;
protected constructor(name:string){
this.name = name
}
}
const person = new Person();//错误不能被实例化,但是可以被继承
类使用readonly修饰符
class Person{
readonly name:string;
readonly age:number = 10;
constructor(name:string,age:number){
//这里可以修改,一旦被构造吼就不能修改
this.name = name;
this.age = age;
}
}
const people = new Person('pp',33);
console.log(people.name); //pp
console.log(people.age); //33
people.name = 'cc'; //报错,只读属性不能被修改
类使用参数属性
class Person{
constructor(readonly name:string,private age:number){
//name属性是只读,private属性是私有
// 直接写constructor可以省事
this.name = name;
this.age = age;
}
}
类的静态属性
class Person{
//静态属性不会跟到实例上面去,通过构造函数访问
static type = 'human';
getType(){
console.log(Person.type);
}
}
console.log(Person.type);
抽象类
abstract class Animal{
//抽象修饰符只能用于抽象类里面,不会具体实现但是继承的子类一定要有这个方法
abstract eat()
}
class Preson extends Animal{
eat(){
}
}
类当接口限制对象
class Animal{
eat(){
console.log('eat');
}
}
class Person extends Animal{
type = 'person'
}
const obj1:Animal = new Person();
const obj2:Person = new Person();
const obj3:Person = {
eat(){
},
type : 'ssss'
//会自己推断,根据上面的类型,这里是只能为string
};
自行回顾
- 类的公共修饰符 默认不写就是public
- 类的私有修饰符 实例不能访问,类里面可以访问,继承的类也不能访问
- 类的保护修饰符,实例不能直接访问,类内核子类都能访问
- 构造函数使用保护修饰符
- 类使用readonly修饰符
- 类使用参数属性
- 类的静态属性
- 抽象类
- 类当接口限制对象
网友评论