TypeScript的类,简单地定义如下:

class Person {
x: number; // 默认为public类型
y: number;
constructor(x1: number, y1: number) { // 默认为public类型
this.x = x1;
this.y = y1;
}
} let test = new Person(12, 34)

ts中,定义一个类使用class关键字,使用new进行类的实例化,constructor关键字用来定义该类的构造函数。

参数属性

什么叫做参数属性,比如上面的x、y字段的声明和构造实例化是分两步进行的,可以归纳到如下一步:

class Person {
constructor(public x1: number, public y1: number) {} // 注意这里的实现
} let test = new Person(12, 34)

继承

使用extends关键字可以实现类之间的继承,包括字段、方法的继承,看个例子:

class Person {
constructor(public x1: number, public y1: number) { }
greet() {
return this.x1 + '-' + this.y1;
}
} class A extends Person {
constructor(x: number, y: number) {
super(x, y);
// ...
}
greet2() {
return this.greet()
}
} let test = new A(12, 23);
console.log('extends from Person: ', test.greet()); // extends from Person: 12-23
console.log('self method: ', test.greet2()); // self method: 12-23
注意:
派生类包含了一个构造函数,它必须调用 super(),它会执行基类的构造函数。而且,在构造函数里访问 this的属性之前,我们一定要调用 super()。 这个是TypeScript强制执行的一条重要规则。
当然,调用super之后在A类中你可以像Person类中那样进行后续处理。

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.`);
}
} let animal = new Animal('rabbit 兔子');
animal.move(1); // rabbit 兔子 moved 1m.
animal.name = '狗熊,忘了英文咋写了';
animal.move(200); // 狗熊,忘了英文咋写了 moved 200m.

private修饰符

private修饰符可以表示字段或者方法是私有的,也就是只在当前类中有效,出了该类是无法访问的,举个栗子:

class Animal {
private name: string;
constructor(theName: string) { this.name = theName; }
} class Rhino extends Animal {
constructor(public age: number) { super("Rhino"); }
} let test = new Animal('狗娃');
// test.name // wrong!访问不到,因为name私有 let test2 = new Rhino(23);
test2.age // 23

protected修饰符

用protected修饰的字段只能在当前类及其子类中访问,被protected修饰的构造函数,构造函数所在的类不能直接直接进行new操作,但是该构造可以被子类继承,从而子类进行重新构造,但是还要首先调用super。

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' 的构造函数是被保护的.可以被继承,不能直接new

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 是只读的.

get和set存取器

对于private字段,一般我们会在class中使用存取器进行赋值及调用,这就是get和set的作用。

class Person {
private _name: string;
set name(theName: string) {
console.log('-----------')
this._name = theName;
}
get name(): string {
return this._name + '********';
}
} let test = new Person();
test.name = 'admin'
console.log(test.name)

输出如下:

-----------
admin********
注意:
get存取器必须要有返回值,没有返回值可以写void返回,返回不确定可以使用any类型。

静态属性

静态属性定义时,直接在属性或字段前面加上static修饰即可。

class Grid {
static origin = { x: 0, y: 0 };
static test;
constructor (public scale: number) { }
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;
}
testValue() {
console.log('testing: ', Grid.test);
}
} let grid1 = new Grid(1.0); // 1x scale
let grid2 = new Grid(5.0); // 5x scale console.log(grid1.calculateDistanceFromOrigin({x: 10, y: 10})); // 14.142135623730951
console.log(grid2.calculateDistanceFromOrigin({ x: 10, y: 10 })); // 2.8284271247461903
console.log(grid1.testValue()); // testing: undefined
注意:
static字段调用的时候直接使用:类名.字段名 调用,实例字段使用:(new Class).字段名 调用,当然class内部直接使用this调用。

抽象类

使用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(); // 错误: 方法在声明的抽象类中不存在 let accountingDepartment: AccountingDepartment;
accountingDepartment = new AccountingDepartment();
accountingDepartment.generateReports();
注意:
1、abstract的class不能直接被new,只能被extends
2、abstract的method必须被子类实现

TypeScript学习笔记之类的更多相关文章

  1. Typescript 学习笔记七:泛型

    中文网:https://www.tslang.cn/ 官网:http://www.typescriptlang.org/ 目录: Typescript 学习笔记一:介绍.安装.编译 Typescrip ...

  2. Typescript 学习笔记六:接口

    中文网:https://www.tslang.cn/ 官网:http://www.typescriptlang.org/ 目录: Typescript 学习笔记一:介绍.安装.编译 Typescrip ...

  3. Typescript 学习笔记五:类

    中文网:https://www.tslang.cn/ 官网:http://www.typescriptlang.org/ 目录: Typescript 学习笔记一:介绍.安装.编译 Typescrip ...

  4. Typescript 学习笔记四:回忆ES5 中的类

    中文网:https://www.tslang.cn/ 官网:http://www.typescriptlang.org/ 目录: Typescript 学习笔记一:介绍.安装.编译 Typescrip ...

  5. Typescript 学习笔记二:数据类型

    中文网:https://www.tslang.cn/ 官网:http://www.typescriptlang.org/ 目录: Typescript 学习笔记一:介绍.安装.编译 Typescrip ...

  6. Typescript 学习笔记三:函数

    中文网:https://www.tslang.cn/ 官网:http://www.typescriptlang.org/ 目录: Typescript 学习笔记一:介绍.安装.编译 Typescrip ...

  7. Typescript 学习笔记一:介绍、安装、编译

    前言 整理了一下 Typescript 的学习笔记,方便后期遗忘某个知识点的时候,快速回忆. 为了避免凌乱,用 gitbook 结合 marketdown 整理的. github地址是:ts-gitb ...

  8. TypeScript学习笔记(八):1.5版本之后的模块和命名空间

    我之前有写过TS1.5版本之前的“模块”的笔记:TypeScript学习笔记(七):模块 但是TS这里的模块和在ECMAScript 2015里的模块(即JS原生支持了模块的概念)概率出现了混淆,所以 ...

  9. typescript学习笔记(三)---接口

    关于第二章的学习笔记是变量声明. 接口:TypeScript的核心原则之一是对值所具有的结构进行类型检查. 它有时被称做“鸭式辨型法”或“结构性子类型化”. 在TypeScript里,接口的作用就是为 ...

  10. typescript学习笔记(一)---基础变量类型

    作为一个前端开发者,学习新技术跟紧大趋势是必不可少的.随着2019年TS的大火,我打算利用一个月的时间学习这门语言.接下来的几篇文章是我学习TS的学习笔记,其中也会掺杂一些学习心得.话不多说,先从基础 ...

随机推荐

  1. [转载] 基于zookeeper、连接池、Failover/LoadBalance等改造Thrift 服务化

    转载自http://blog.csdn.net/zhu_tianwei/article/details/44115667 http://blog.csdn.net/column/details/sli ...

  2. [转载] linux中文件描述符fd和文件指针flip的理解

    转载自http://www.cnblogs.com/Jezze/archive/2011/12/23/2299861.html 简单归纳:fd只是一个整数,在open时产生.起到一个索引的作用,进程通 ...

  3. CLR类型设计之参数传递

    写到这篇文章的时候,笔者回忆起来以前的开发过程中,并没有注意参数的传递是以值传递还是引用传递的,也是第一次了解到可变参数params,常用的不一定就代表理解,可能只是会用.接下来我们就一起回忆一下关于 ...

  4. JavaScript学习笔记(二)——字符串

    在学习廖雪峰前辈的JavaScript教程中,遇到了一些需要注意的点,因此作为学习笔记列出来,提醒自己注意! 如果大家有需要,欢迎访问前辈的博客https://www.liaoxuefeng.com/ ...

  5. Redis学习-内存优化

    以下为个人学习Redis的备忘录--内存优化 1.随时查看info memory,了解内存使用状况:127.0.0.1:6379> info memory# Memoryused_memory: ...

  6. MS10_087漏洞学习研究

    类别:栈溢出,fileformat类别漏洞 描述: This module exploits a stack-based buffer overflow in the handling of the ...

  7. sqlmap命令

    -u #注入点 -f #指纹判别数据库类型 -b #获取数据库版本信息 -p #指定可测试的参数(?page=1&id=2 -p "page,id") -D "& ...

  8. shopxx------list列表回显修改尝试

    需求:在商品列表展示页面增加一列 一.修改模板 1.列表页面对应的freemarker模板位置 /shopxx/WebContent/WEB-INF/template/admin/product/li ...

  9. [动态规划]P1854 花店橱窗布置

    题目描述 某花店现有F束花,每一束花的品种都不一样,同时至少有同样数量的花瓶,被按顺序摆成一行,花瓶的位置是固定的,从左到右按1到V顺序编号,V是花瓶的数目.花束可以移动,并且每束花用1到F的整数标识 ...

  10. 一个页面tab标签切换,都有scroll事件的解决办法

    当前页有多个tab,如果都有scroll事件, 先解绑$(window).off('scroll') 再执行scroll就不可以了,多个标签就不会互相干扰: 给你们个例子: //标签切换    $(' ...