关于类的基本用法,可以参阅TypeScript class 类介绍一章节。
下面分别介绍一下类的访问修饰符:
一.public访问修饰符:
在TypeScript中,成员都默认为public(在C#等语言则需要显式的规定);可以省略。
代码实例如下:class Antzone {
public webName: string;
public constructor(webName: string) { this.webName = webName; }
public show(age: number) {
console.log(`${this.webName} 成立 ${age}年了.`);
}
}
let antzone=new Antzone("Downzz.com");
antzone.show(4);
使用public修饰的成员,可以在类的内外自由访问。
二.private修饰符:
当成员被标记成private时,就不能在声明它的类的外部访问。
代码实例如下:class Antzone {
private webName: string;
public constructor(webName: string) { this.webName = webName; }
public show(age: number) {
console.log(`${this.webName} 成立 ${age}年了.`);
}
}
let antzone=new Antzone("Downzz.com");
antzone.webName;
由于webName是私有类型,所以会报错,截图如下:
三.protected访问修饰符:
protected与private行为相似,但有一点不同,protected成员在派生类中可以访问。
代码实例如下:class Person {
protected name: string;
constructor(name: string) { this.name = name; }
}
class Employee extends Person {
private department: string;
constructor(name: string, department: string) {
super(name)
this.department = department;
}
public getElevatorPitch() {
return `Hello, my name is ${this.name} and I work in ${this.department}.`;
}
}
let howard = new Employee("Howard", "Sales");
console.log(howard.getElevatorPitch());
console.log(howard.name);
由于父类中的name访问修饰符是protected,所以可以在它的派生类中访问:public getElevatorPitch() {
return `Hello, my name is ${this.name} and I work in ${this.department}.`;
}
所以上面的代码是正确的,但是不能够在类的外部访问:console.log(howard.name)
所以上面的代码会报错,截图如下:
四.readonly修饰符:
使用readonly关键字将属性设置为只读的。
只读属性必须在声明时或构造函数里被初始化,代码实例如下:class Antzone {
readonly webName: string;
public constructor(webName: string) { this.webName = webName; }
public show(age: number) {
console.log(`${this.webName} 成立 ${age}年了.`);
}
}
let antzone=new Antzone("Downzz.com");
antzone.webName="蚂蚁奋斗";
由于webName是只读的,所以在非声明或者构造函数里给它赋值会报错。