web前端全系列 教程
1839个小节阅读:2243.2k
目录
鸿蒙应用开发
C语言快速入门
JAVA全系列 教程
面向对象的程序设计语言
Python全系列 教程
Python3.x版本,未来主流的版本
人工智能 教程
顺势而为,AI创新未来
大厂算法 教程
算法,程序员自我提升必经之路
C++ 教程
一门通用计算机编程语言
微服务 教程
目前业界流行的框架组合
web前端全系列 教程
通向WEB技术世界的钥匙
大数据全系列 教程
站在云端操控万千数据
AIGC全能工具班
A A
White Night
在类中声明的属性与方法,可以添加访问修饰符控制可被访问的范围
TypeScript 可以使用三种访问修饰符(Access Modifiers),分别是 public
、private
和 protected
public
修饰的属性或方法是公有的,可以在任何地方被访问到,默认所有的属性和方法都是 public
的private
修饰的属性或方法是私有的,不能在声明它的类的外部访问protected
修饰的属性或方法是受保护的,它和 private
类似,区别是它在子类中也是允许被访问的public
我们可以自由的访问程序里定义的成员,在 TypeScript 里,成员都默认为 public
name
被设置为了 public
,所以直接访问实例的 name
属性是允许的
xxxxxxxxxx
class Animal {
public name: string;
public constructor(theName: string) {
this.name = theName
}
public move(distanceInMeters: number) {
console.log(`${this.name} moved ${distanceInMeters}m.`);
}
}
private
当成员被标记成 private
时,它就不能在声明它的类的外部访问
xxxxxxxxxx
class Animal {
private name: string;
public constructor(theName: string) {
this.name = theName
}
public move(distanceInMeters: number) {
console.log(`${this.name} moved ${distanceInMeters}m.`);
}
}
let a = new Animal("动物")
console.log(a.name) // Property 'name' is private and only accessible within class 'Animal'.
protected
protected
修饰符与 private
修饰符的行为很相似,但有一点不同, protected
成员在派生类(子类)中仍然可以访问
xxxxxxxxxx
class Animal {
protected name: string;
public constructor(theName: string) {
this.name = theName
}
}
class Cat extends Animal{
constructor(theName:string){
super(theName)
}
public move(distanceInMeters: number) {
console.log(`${this.name} moved ${distanceInMeters}m.`);
}
}
let c = new Cat("猫")
c.move(10)
实时效果反馈
1. 在TypeScript中,访问修饰符下列那个子类可以访问:
A pub
B private
C protected
D class
答案
1=>C