LayaBox---TypeScript---类
目录
1.普通类的示例
2.继承
3.公共、私有与受保护的修饰符
public:
private:
protected:
4.readonly修饰符
5.存取器
6.静态属性--static
7.抽象类--abstract
8.把类当作接口使用
1.普通类的示例
class Greeter{greeting: string;constructor(msg: string){this.greeting = msg;}greet(){return "hello, " + this.greeting;}
}let greeter = new Greeter("world");
2.继承
//一个简单的继承示例
class Animal{move( distanceInMeters: number=0 ){console.log('Animal moved ${distanceInMeters}m.');}
}class Dog extends Animal{bark(){console.log( 'Woof! Woof!' );}
}Const dog = new Dog();
dog.bark();
dog.move(10);
dog.bark();
//一个复杂的继承示例
class Animal {name: string;constructor(theName: string) { this.name = theName; }move(distanceInMeters: number = 0) {console.log(`${this.name} moved ${distanceInMeters}m.`);}
}class Snake extends Animal {constructor(name: string) { super(name); }move(distanceInMeters = 5) {console.log("Slithering...");super.move(distanceInMeters);}
}class Horse extends Animal {constructor(name: string) { super(name); }move(distanceInMeters = 45) {console.log("Galloping...");super.move(distanceInMeters);}
}let sam = new Snake("Sammy the Python");
let tom: Animal = new Horse("Tommy the Palomino");sam.move();
tom.move(34);
与前一个简单的继承示例不同的是,它的派生类包含了一个构造函数,它必须调用super(),它会执行基类的构造函数。
⚠️注意:在构造函数里访问this的属性前,一定要调用supper()。这是ts强制执行的一条规则。
3.公共、私有与受保护的修饰符
3.1 与C#等语言不同,ts里成员默认都是public属性
public:
//也可以明确的将成员标记成public
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 时,它就不能在声明它的类的外部访问
class Animal {private name: string;constructor(theName: string) { this.name = theName; }
}new Animal("Cat").name; // 错误: 'name' 是私有的.
TypeScript使用的是结构性类型系统。 当我们比较两种不同的类型时,并不在乎它们从何处而来,如果所有成员的类型都是兼容的,我们就认为它们的类型是兼容的。
然而,当我们比较带有 private
或 protected
成员的类型的时候,情况就不同了。 如果其中一个类型里包含一个 private
成员,那么只有当另外一个类型中也存在这样一个 private
成员, 并且它们都是来自同一处声明时,我们才认为这两个类型是兼容的。 对于 protected
成员也使用这个规则。
class Animal {private name: string;constructor(theName: string) { this.name = theName; }
}class Rhino extends Animal {constructor() { super("Rhino"); }
}class Employee {private name: string;constructor(theName: string) { this.name = theName; }
}let animal = new Animal("Goat");
let rhino = new Rhino();
let employee = new Employee("Bob");animal = rhino;
animal = employee; // 错误: Animal 与 Employee 不兼容.
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); // 错误注意,我们不能在 Person类外使用 name,但是我们仍然可以通过 Employee类的实例方法访问,因为 Employee是由 Person派生而来的。
构造函数也可以被标记成 protected
。 这意味着这个类不能在包含它的类外被实例化,但是能被继承。
class Person {protected name: string;protected constructor(theName: string) { this.name = theName; }
}// Employee 能够继承 Person
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");
let john = new Person("John"); // 错误: 'Person' 的构造函数是被保护的.
4.readonly修饰符
可以使用 readonly
关键字将属性设置为只读的。 只读属性必须在声明时或构造函数里被初始化。
class Octopus {readonly name: string;readonly numberOfLegs: number = 8;constructor (theName: string) {this.name = theName;}
}
let dad = new Octopus("Man with the 8 strong legs");
dad.name = "Man with the 3-piece suit"; // 错误! name 是只读的.
上面的例子,我们在Octopus里定义了一个只读成员name和一个参数为theName的构造函数,且将theName的值赋给了name。
而参数属性可以方便的让我们在一个地方定义并初始化成员。
class Octopus {readonly numberOfLegs: number = 8;constructor(readonly name: string) {}
}
如上,我们是如何舍弃了 theName
,仅在构造函数里使用 readonly name: string
参数来创建和初始化 name
成员。 我们把声明和赋值合并至一处。
5.存取器
TypeScript支持通过getters/setters来截取对对象成员的访问。
class Employee {fullName: string;
}let employee = new Employee();
employee.fullName = "Bob Smith";
if (employee.fullName) {console.log(employee.fullName);
}
下面这个版本里,我们先检查用户密码是否正确,然后再允许其修改员工信息。 我们把对 fullName
的直接访问改成了可以检查密码的 set
方法。 我们也加了一个 get
方法,让上面的例子仍然可以工作。
let passcode = "secret passcode";class Employee {private _fullName: string;get fullName(): string {return this._fullName;}set fullName(newName: string) {if (passcode && passcode == "secret passcode") {this._fullName = newName;}else {console.log("Error: Unauthorized update of employee!");}}
}let employee = new Employee();
employee.fullName = "Bob Smith";
if (employee.fullName) {alert(employee.fullName);
}
⚠️注意:
1.存取器要求你将编译器设置为输出ECMAScript 5或更高。 不支持降级到ECMAScript 3。
2.只带有 get
不带有 set
的存取器自动被推断为 readonly
。
6.静态属性--static
我们使用 static
定义 origin
,因为它是所有网格都会用到的属性。 每个实例想要访问这个属性的时候,都要在 origin
前面加上类名。 如同在实例属性上使用 this.
前缀来访问属性一样
class Grid {static origin = {x: 0, y: 0};calculateDistanceFromOrigin(point: {x: number; y: number;}) {let xDist = (point.x - Grid.origin.x);let yDist = (point.y - Grid.origin.y);return Math.sqrt(xDist * xDist + yDist * yDist) / this.scale;}constructor (public scale: number) { }
}let grid1 = new Grid(1.0); // 1x scale
let grid2 = new Grid(5.0); // 5x scaleconsole.log(grid1.calculateDistanceFromOrigin({x: 10, y: 10}));
console.log(grid2.calculateDistanceFromOrigin({x: 10, y: 10}));
7.抽象类--abstract
抽象类做为其它派生类的基类使用。 它们一般不会直接被实例化。
1.不同于接口,抽象类可以包含成员的实现细节。
abstract class Animal {abstract makeSound(): void;move(): void {console.log('roaming the earch...');}
}
2.抽象类中的抽象方法不包含具体实现并且必须在派生类中实现。
3.抽象方法必须包含 abstract
关键字并且可以包含访问修饰符。
abstract class Department {constructor(public name: string) {}printName(): void {console.log('Department name: ' + this.name);}abstract printMeeting(): void; // 必须在派生类中实现
}class AccountingDepartment extends Department {constructor() {super('Accounting and Auditing'); // 在派生类的构造函数中必须调用 super()}printMeeting(): void {console.log('The Accounting Department meets each Monday at 10am.');}generateReports(): void {console.log('Generating accounting reports...');}
}let department: Department; // 允许创建一个对抽象类型的引用
department = new Department(); // 错误: 不能创建一个抽象类的实例
department = new AccountingDepartment(); // 允许对一个抽象子类进行实例化和赋值
department.printName();
department.printMeeting();
department.generateReports(); // 错误: 方法在声明的抽象类中不存在
8.把类当作接口使用
class Point {x: number;y: number;
}interface Point3d extends Point {z: number;
}let point3d: Point3d = {x: 1, y: 2, z: 3};
LayaBox---TypeScript---类相关推荐
- .NET手撸绘制TypeScript类图——下篇
.NET手撸绘制TypeScript类图--下篇 在上篇的文章中,我们介绍了如何使用 .NET解析 TypeScript,这篇将介绍如何使用代码将类图渲染出来. 类型定义渲染 不出意外,我们继续使用 ...
- .NET手撸绘制TypeScript类图——上篇
.NET手撸绘制TypeScript类图--上篇 近年来随着交互界面的精细化, TypeScript越来越流行,前端的设计也越来复杂,而 类图正是用简单的箭头和方块,反映对象与对象之间关系/依赖的好方 ...
- typescript get方法_.NET手撸绘制TypeScript类图——上篇
.NET手撸绘制TypeScript类图--上篇 近年来随着交互界面的精细化,TypeScript越来越流行,前端的设计也越来复杂,而类图正是用简单的箭头和方块,反映对象与对象之间关系/依赖的好方式. ...
- TypeScript 类(Class)
TypeScript 类(Class) 自 ES6 起,终于迎来了 class,对于开发者来说,终于可以使用基于类的面向对象式编程.TypeScript 在原 ES6 中类的基础上,还添加了一些新的功 ...
- 三分钟快速了解typeScript 类
typeScript 类 类描述了所创建的对象共同的属性和方法. 类的定义 继承 类里面的修饰符 静态属性 静态方法 抽象类 继承 多态 类的定义 class person {name:string; ...
- Typescript类,泛型,各种类型工具
一.TypeScript 类 一个类可以包含以下几个模块: 1.属性 1.1 类属性 1.2 实例属性 2.构造函数(在python中叫初始化函数) 该函数在类实例化时会被立即调用 3.方法(也是函数 ...
- 05 TypeScript 类的使用
目录 1.1 类的基本使用 1.2 类的继承 1.3 static和instanceof 1.4类中的修饰符 1.5 getter与setter 1.6 抽象类 1.7 implements子句 1. ...
- TypeScript类
目录 1-1.类的基本使用 1-2.类的继承 1-3.static与instanceof 1-4.类中的修饰符 1-5.getter与setter 1-6.抽象类 1-7.implements子句 1 ...
- TypeScript = 类
TypeScript笔记 5. TypeScript => 类 // 1. ts如何定义类 /* class Person {name:string;constructor(name:strin ...
- TypeScript 接口和TypeScript类
目录 一.TypeScript 接口 1.TypeScript 接口的定义和简单使用 2.联合类型和接口 3.接口和数组 4.接口继承 二.TypeScript 类 1.TypeScript 类的定义 ...
最新文章
- 实战篇:Security+JWT组合拳 | 附源码
- C++实现通过UDP传输文件
- OC如何跳到系统设置里的各种设置界面
- 欢乐纪中A组周六赛【2019.5.18】
- 工作71:nexttick使用
- 集腋成裘-10-ECharts -未知-03
- angularjs php 实例下载,AngularJS Eclipse 1.2.0 插件下载
- css-选择器-进阶-属性选择器-组选择器-nth选择器
- intval0.57100 php_关于PHP浮点数之 intval((0.1+0.7)*10) 为什么是7
- java sax解析器_Java SAX解析器示例
- 【金万维】天联高级版客户端打开U8报错:未监听端口
- 防止被偷窥和修改 Office文档保护秘笈
- 如何在电脑上录制qq语音
- 【文件监控】之一:理解 ReadDirectoryChangesW part1
- swiper、fullPage、hammer几种滑动插件对比
- Ubuntu20.04LTS 安装QQ 微信 钉钉 最简单,最好用的方式!
- Grandmaster 楼教主回忆录
- 初学linux(-)
- java启动100线程_Java-多线程
- PCLINT(2):MVG NEST LOC (圈复杂度 嵌套深度 代码行数)