typescript class类中 public、private、protected、static、abstract 区别

typescript class类中 public、private、protected、static、abstract 区别,第1张

类的修饰符 public

默认修饰符
可以自由的访问程序里定义的成员

private

只能在类内部访问

class Animal {
    private name: string;
    constructor(theName: string) { this.name = theName; }
}

let zoo = new Animal('panda')
zoo.name // Property 'name' is private and only accessible within class 'Animal'.
protected

在类内部和子类中可以访问

class Animal {
    protected name: string;
    constructor(theName: string) { this.name = theName; }
}

class Panda extends Animal {
  constructor() {
    super('xiangxiang')
    console.log(this.name) // xiangxiang
  }
}

let pan = new Panda()
readonly

只读,在内部初始化

class Panda {
    readonly name: string;
    constructor(theName: string) { this.name = theName; }
}

let pan = new Panda('panda')

pan.name = 'cat' // Cannot assign to 'name' because it is a constant or a read-only property.
静态属性 static

不能通过实例访问

class Animal {
    static myName: string;
    constructor(theName: string) { Animal.myName = theName; }
}

class Panda extends Animal {
  constructor() {
    super('xiangxiang')
  }
}
let ani = new Animal('lala')
ani.myName // Property 'myName' is a static member of type 'Animal'

let pan = new Panda()
console.log(Panda.myName)
抽象类 abstract

抽象类中的抽象方法不包含具体实现并且必须在派生类中实现

abstract class Animal {
	sayname() {
		console.log('this is an animal');
	}
	// 抽象方法不具体实现
	abstract say(): void;
}
class Panda extends Animal {
	// 子类必须实现父类抽象方法
	say() {
		console.log('my name is xiangxiang');
	}
}
// let ani = new Animal(); // 抽象类不可以被实例化
let pan = new Panda();
pan.sayname(); // this is an animal
pan.say(); // my name is xiangxiang

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1322978.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-12
下一篇 2022-06-12

发表评论

登录后才能评论

评论列表(0条)

保存