[TypeScript] Creating a Class in TypeScript
2024-08-31 21:02:10
Typescript classes make traditional object oriented programming easier to read and write. In this lesson we learn about class syntax, what the constructor is and some interesting variable features.
interface Opponent {
health: number;
alias: string;
} class ComicBookCharacter { private team: {
name: string;
members: ComicBookCharacter[]
}; static createAndAssignTeam(teamName: string, members: ComicBookCharacter[]) {
let team = {
name: teamName,
members: members
}; members.forEach((member)=>{
member.team = team;
})
} constructor(public alias: string,
public health: number,
public strength: number,
private secretIdentity: string) { } getTeamName(){
console.log(`${this.alias} is from ${this.team.name}`);
return this.team.name;
} attackFunc(opponent: Opponent, attackWith) {
opponent.health -= attackWith;
console.log(`${this.alias} attacked ${opponent.alias}, who's health = ${opponent.health}`);
return opponent.health;
} getSecretIdentity() {
if (this.secretIdentity) {
console.log(`${this.alias} is ${this.secretIdentity}`);
} else {
console.log(`${this.alias} has no secret identity`);
}
}
} const Sparky = new ComicBookCharacter("Sparky", , , "Thunder");
const Rainer = new ComicBookCharacter("Rainer", , , "Water"); ComicBookCharacter.createAndAssignTeam('Eevee', [Sparky,Rainer]);
Sparky.getTeamName();
To review, we've learned about access modifiers and the difference between public
and private
. The constructor is run when the class
instance is initialized, and the shorthand for setting class properties allows us to write less code. We've learned that static
properties can only be referenced from the class, not the instance, and how static
properties have access to an instances
private properties.
最新文章
- MySQL数据表生成ER图
- 【uva】1220 Party at Hali-Bula
- oc-23-static
- PHP: 深入pack/unpack 字节序
- ArcSDE 10.1安装、配置、连接 (SQL Server 2008)
- String.PadLeft - 格式对齐
- mysql学习(五)-字段属性
- HDU 1498 50 years, 50 colors(最小点覆盖,坑称号)
- [贪心][高精]P1080 国王游戏(整合)
- js文件加载优化
- Java开发笔记(四十)日期与字符串的互相转换
- JS 实现兼容IE图片向左或向右翻转
- apache启动失败
- Perl的输出:print、say和printf、sprintf
- JS获取验证码后倒计时不受刷新及关闭影响
- Vue基础进阶 之 自定义指令
- 如何实现浏览器向服务器伪造refer?
- url中含有%
- Zookeeper命令行zkCli.sh&;zkServer.sh的使用(四)
- Delphi 实现不规则窗体