ts 修饰符_TypeScript 类访问修饰符_TS教程

关于类的基本用法,可以参阅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是只读的,所以在非声明或者构造函数里给它赋值会报错。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值