typescript-类

介绍

传统的JavaScript程序使用函数和基于原型的继承来创建可重用的组件,单对于熟悉使用面向对象方式的程序员来讲就有些棘手,因为他们用的是基于类的继承并且对象是由类构建出来的。从ES6开始,JavaScript程序员江能够使用基于类的面向对象方式。使用TypeScript。我们允许开发者现在就使用这些特性,并且编译后的JavaScript可以在所有主流浏览器和平台运行

class Greeter {
  greeting: string

  constructor (message: string) {
    this.greeting = message
  }
  greet () {
    return `Hello ${this.greeting}`
  }

}
let greeter = new Greeter('world')
console.log(greeter)

由例子可以看出,我们声明了一个Greeter的类,这个类有三个成员: 一个叫greeting的属性,一个构造函数和一个greet的方法。

你会注意到,我们在引用任何一个类成员的时候都用到了this、他表示我们访问的是类成员

最后一行,使用new 构造了Greeter类的一个示例。他会调用之前定义的构造函数,创建一个Greeter类型的新对象,并执行构造函数初始化它

继承

在TypeScript里,我们可以使用常用的面向对象模式、基于类的程序设计中一种最基本的模式是允许使用继承来扩展现有的类。

class Animal {
  move (distanceInMeters: number = 0) {
    console.log(`Animal moved ${distanceInMeters}`)
  }
}
class Dog extends Animal{
  bark () {
    console.log('Woof!')
  }
}
const dog = new Dog()
dog.bark()
dog.move(123)
dog.bark()

这个例子展示了最基本的继承:类从基类中继承了属性和方法。这里,Dog是一个派生类,它派生自Animal基类,通过extend关键字。派生类通常被称作子类,基类通常被称作超类

因为Dog继承了Animal的功能,因此我们可以创建一个Dog的实例,它能够bark()和move()

下面来看更复杂的例子

class Animal1 {
  name: string
  constructor (theName: string) {
    this.name = theName
  }
  move(distanceInMeters: number = 0) {
    console.log(`${this.name} moved ${distanceInMeters}`)
  }
}
class Snake extends Animal1 {
  constructor (name: string) {super(name)}
  move(distanceInMeters = 5) {
    console.log('Slithering...')
    super.move(distanceInMeters)
  }
}
class Horse extends Animal1{
  constructor (name) {super(name)}
  move (distanceInMeters: number = 45) {
    console.log('Galloping...')
    super.move(distanceInMeters)
  }
}
let sam = new Snake('Sammy the Python')
let tom: Animal1 = new Horse('Tommy the palomino')
console.log(sam, tom)
sam.move()
tom.move(34)

这个例子展示了一些上面没有提到的特性。这一次,我们使用extends关键字创建了Animal1的两个子类: Horse 和Snake

与前一个例子的不同点是,派生类包含了一个构造函数。它必须调用supper(),他会执行基类的构造函数,而且,在构造函数里访问this的属性之前,我们一定要调用super()。这个是typeScript强制执行的一条重要规则。

这个例子演示了如何在子类里可以重写父类的方法。Snake类和Horse类都创建了move方法,他们重写了从Animal继承来的move方法,使得move方法根据不同的类而具有不用的功能。注意及时tom被声明为Animal1类型,但因为它的值是HOrse,调用tom.move(34)时候,它会低啊用Horse里重写的方法。

公共,私有与手保护的修饰符

默认为public

在上面的例子里,我们可以自由的访问程序里定义的程序。如果你对其他语言中的类比较了解,就会注意到我们在之前的代码里并没有使用public来做修饰;

你也可以明确的将一个成员标记成public。我们可以用下面的方式来重写上面的Animal类

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 Animal2 {
  private name: string
  constructor (theName: string) {
    this.name = theName
  }
}
new Animal2('Cat').name // Property 'name' is private and only accessible within class 'Animal2'.

TypeScript使用的是结构性类型系统。当我们比较两种不同的类型时,并不在乎它们从何处而来,如果所有成员的类型都是兼容的,我们就认为它们的类型是兼容的。

然后,当我们比较带有private活protected成员的类型的时候,情况就不同了,如果其中一个类型里包含一个private成员,那么只有当另一个类型中也存在这样一个private成员,并且它们都是来自同一处声明时候,我们才认为这两个类型是兼容的。对于protected成员也使用这个规则

下面来看一个例子,更好地说明了这一点

class Animal_2 {
  private name: string
  constructor (theName: string) {
    this.name = theName
  }
}
class Rhino extends Animal_2{
  constructor () {super('Rhino')}
}
class Employee {
  private name: string

  constructor (theName:string) {
    this.name = theName

  }
}
let animal = new Animal_2('Gpat')
let rhino = new Rhino()
let emoloyee = new Employee('Bob')
animal = rhino
animal = emoloyee //  Type 'Employee' is not assignable to type 'Animal_2'.
  // Types have separate declarations of a private property 'name'.

这个例子中有Animal_2和Rhino两个类,Rhino是Animal_2的子类,还有一个Employee类,其类型看上去与Animal是相同的。我们创建了几个这些类型的实例,并相互赋值来看看会发生什么。因为Animal_2和Rhino共享了来自Animal_2里的私有成员定义private name: string,因此他们是兼容的。然而Employee却不是这样。当把Employee赋值给Animal_2的时候,得到一个错误,说明他们的类型不兼容。尽管,Employee里也有一个私有成员name,但它明显不是Animal_2里面定义的那个

理解protected

protected修饰符与private修饰符的行为很相似,但有一点不同,protected成员在派生类中仍然可以访问

class Person {
  protected name: string
  constructor (name: string) {
    this.name = name
  }
}
class Employee_1 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_1('Howard', 'Sales')
console.log(howard.getElevatorPitch())
console.log(howard.name) //  Property 'name' is protected and only accessible within class 'Person' and its subclasses.

注意,我们不能在Person类外使用name,但是我们仍然可以通过Employee_1类的实例方法访问,因为Employee_1是由Person派生而来的

构造函数也可以被标记成Protected。这意味着这个类不能在包含它的类外被实例化。但是能被继承,比如:

class Person {
  protected name: string
  protected constructor (theName: string) {
    this.name = theName
  }
}
class Employee_1 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_1('Howard', 'Sales')
let john = new Person('John') //  Constructor of class 'Person' is protected and only accessible within the class declaration.

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" // Cannot assign to 'name' because it is a read-only property.

参数属性

在上面的例子中,我们必须在Octopus类里定义一个制度成员name和一个参数为theName的构造函数,并且立刻将theName的值付给name,这种情况经常会遇到。参数属性可以方便地让我们在一个地方定义并初始化成员。下面的例子是对之前Octpus类的修改版,使用了参数属性

class  Octopus {
  readonly numberOfLegs: number = 8
  constructor (readonly name: string) {}
}
const o = new Octopus('ooo')
console.log(o.name)

注意看我们是如何舍弃了theName,仅在构造函数里使用readonly name: string参数来创建和初始化name成员。我们把声明和赋值合并至一处。

参数属性通过给构造函数前面添加一个访问限定符来声明。使用private限定一个参数属性会声明并初始化一个私有成员;对于pubilc和protected来说也是一样的。

存取器

typeScript智齿通过getters/setters来截取对对象成员的访问。它能帮助你有效的控制对对象成员的访问。

下面来看如何把一个简单的类改写成使用get和set。首先,我们从一个没有使用存取的例子开始。

class Employee_1 {
  fullName: string
}
let employee = new Employee_1()
employee.fullName = 'Bob Smith'
if (employee.fullName) {
  console.log(employee.fullName)
}

我们可以随意的设置fullName,这是非常方便的,但是这也可能会带来麻烦。

下面这个版本里,我们可以先检查用户密码是否正确,然后在允许其修改员工信息。我们把对fullName的直接访问改成了可以检查密码的set方法。我们也加了一个get方法,让上面的例子

let passcode = "secret passcode"
class Employee_1 {
  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_1()
employee.fullName = 'Bob Smith'
if (employee.fullName) {
  console.log(employee.fullName)
}

我们可以修改一下密码,来验证一下存取器是否工作的。当密码不对时候,会提示我们没有权限去修改员工。

对于存取器有下面几点需要注意的:

首先,存取器要求你讲编译器设置为输出的ECMAScript 5 或者更高。不支持降级到ECMAScript3.其次,只有带有get不带有set的存取器自动被推断为readonly。这在从代码生成.d.ts文件时是又帮助的,因为利用这个属性的用户会看到不允许够改变它的值。

静态属性

到目前位置,我们值讨论了类的势力成员,那些晋档类被实例化的时候才会被初始化的属性。我们也可以创建类的静态成员,这些属性存在于类本身上面而不是类的实例上。在这个例子里,我们使用static定义origin,因为它是所有网格都会用到的属性。每个实例想要访问这个属性的时候,都要在origin前面加上类名。如同在实例属性上使用this.前缀来访问属性一样,这里我们使用Grid.来访问静态属性

static修饰的属性,可以直接调用,否则必须用new新对象才能调用

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)
let grid2 = new Grid(5.0)
console.log(grid1.calculateDistanceFromOrigin({x:10,y:10}))
console.log(grid2.calculateDistanceFromOrigin({x: 10, y: 10}))

抽象类

抽象类作为其他派生类的基类使用。它们一般不会直接被实例化。不同于接口,抽象类可以包含成员实现细节。abstract关键字是用于定义抽象类和在抽象类内部定义抽象方法。

abstract class Animal_1  {
  abstract makeSound() :void
  move():void{
    console.log('roaming the earch...')
  }
}

抽象类中的抽象方法不包含具体实现并且必须在派生类中实现。抽象方法的语法与接口方法相似。两者都是定义方法签名但不包含方法体。然后,抽象方法必须包含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('AccountingDepartment')} // 在派生类的构造函数中必须调用 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() //Cannot create an instance of an abstract class. 错误: 不能创建一个抽象类的实例
department = new AccountingDepartment() // 允许对一个抽象子类进行实例化和赋值
department.printName()
department.printMeeting()
department.generateReports() //  Property 'generateReports' does not exist on type 'Department'. // 错误: 方法在声明的抽象类中不存在

高级技巧

构造函数

当你在typeScript中声明了一个类的时候,实际上同时声明了很多东西。首先就是类的实例的类型

class Greeter_1 {
  greeting: string
  constructor (message: string) {
    this.greeting = message
  }
  greet() {
    return `Hello,${this.greeting}`
  }
}
let greeter_1:Greeter_1
greeter_1 = new Greeter_1('world')
console.log(greeter_1.greet())

这里我们写了ket greeter:Greeter,意思是Greeter类的实例的类型是Greeter。这对于用过其它面向对象语言的程序员来讲已经是老习惯了

我们也创建了一个叫做构造函数的值。这个函数会在我们使用new创建类实例的时候被调用。下面我们来看看,上面的代码被编译成JavaScript后是什么样子的:

let Greeter = (function () {
    function Greeter(message) {
        this.greeting = message;
    }
    Greeter.prototype.greet = function () {
        return "Hello, " + this.greeting;
    };
    return Greeter;
})();

let greeter;
greeter = new Greeter("world");
console.log(greeter.greet());

上面代码里,let Greeter将被复制为构造函数。当我们调用new并执行了这个函数后,会得到一个类的实例。这个构造函数也包含了类的所有静态属性。换个角度说,我们可以认为类具有实例部分与静态部分这两个部分

让我们稍微修改一下这个例子,看看它们之间的区别

class Greeter_2 {
  static standardGreeting = "hello, there"
  greeting: string
  greet() {
    if (this.greeting) {
      return `hello,${this.greeting}`
    } else {
      return Greeter_2.standardGreeting
    }
  }
}
let greeter_2: Greeter_2
greeter_2 = new Greeter_2()
console.log(greeter_2.greet())

let greeterMaler: typeof Greeter_2 = Greeter_2
greeterMaler.standardGreeting = 'hey there'
let greeter_3:Greeter_2 = new greeterMaler()
console.log(greeter_3.greet())

这个例子里,greeeter_2与之前看到的一样。我们实例化了Greeter_2类,并且使用这个对象。与我们之前看到的一样。

再之后,我们直接使用类。我们创建了一个greeterMaler的变量。这个变量保存了这个类或者说保存了类的构造函数。然后我们使用typeof Greeter_2,意思是去Greeter_2类的类型,而不是实例的类型。或者更确切的说,‘告诉我Greeter_2标识符的类型’,也就是构造函数的类型。这个类型包含了类的所有静态成员和构造函数。之后就和前面一样,我们在greeterMaler上使用new,创建Greeter_2实例。

把类当做接口使用

如上一节所讲的,类定义会创建两个东西:类的实例和一个构造函数。因为类可以创建类型,所以你能够在允许使用接口的地方使用类

class Point {
    x: number;
    y: number;
}

interface Point3d extends Point {
    z: number;
}

let point3d: Point3d = {x: 1, y: 2, z: 3};
posted @ 2022-03-29 15:16  upupupupupgo  阅读(43)  评论(0编辑  收藏  举报