传统的JavaScript程序使用函数和基于原型的继承来创建可重用的组件,但对于熟悉使用面向对象方式的程序员来讲就有些棘手,因为他们用的是基于类的继承并且对象是由类构建出来的。 从ECMAScript 6开始,JavaScript程序员将能够使用基于类的面向对象的方式。

一个简单的小例子

我们在es6中定义一个类需要这么做:

  1. class Animal {
  2. constructor(type){ //构造函数,对象私有的东西
  3. this.type = type;
  4. }
  5. eat(){//方法
  6. console.log('i can eat food')
  7. }
  8. }

在TS中,我们可以这么做:

  1. class Animal {
  2. public name: string;
  3. constructor(name: string) {
  4. this.name = name;
  5. }
  6. public sayHi() {
  7. return `My name is ${this.name}`;
  8. }
  9. }
  10. let a = new Animal("Jack");
  11. console.log(a.sayHi()); // My name is Jack

我们可以看到,和es中类的构造几乎是差不多的。而至于这里的public是什么,先不用着急,下面会讲到。

类的继承

ES6中类的继承是这么实现的:

  1. class Animal {
  2. constructor(type){
  3. this.type = type;
  4. }
  5. eat(){
  6. Animal.say()
  7. console.log('i can eat food')
  8. }
  9. static say(){
  10. console.log('i can say english')
  11. }
  12. }
  13. class Dog extends Animal { //dog是Animal的子类
  14. super(type) //初始化父类构造函数
  15. //如果子类中也有自己的属性,需要写构造函数
  16. constructor(type){
  17. super(type) //必须放在最前面,type可以是亦是,可以是固定的
  18. this.weight = 5;
  19. }
  20. }
  21. let dog = new Dog('dog')
  22. dog.eat()
  23. //log
  24. //i can say english
  25. //i can eat food

在TS中,我们需要这么写:

  1. class Animal {
  2. public name: string;
  3. constructor(name: string) {
  4. this.name = name;
  5. }
  6. public sayHi() {
  7. return `My name is ${this.name}`;
  8. }
  9. }
  10. class Cat extends Animal {
  11. constructor(name: string) {
  12. super(name); // 调用父类的 constructor(name)
  13. console.log(this.name);
  14. }
  15. public sayHi() {
  16. return "Meow, " + super.sayHi(); // 调用父类的 sayHi()
  17. }
  18. }

官方给我们提供了一个看似很复杂的例子,我可以看看一下:

  1. class Animal {
  2. public name: string;
  3. constructor(theName: string) { this.name = theName; }
  4. public move(distanceInMeters: number = 0) {
  5. console.log(`${this.name} moved ${distanceInMeters}m.`);
  6. }
  7. }
  8. class Snake extends Animal {
  9. constructor(name: string) { super(name); }
  10. public move(distanceInMeters: number = 5) {
  11. console.log("Slithering...");
  12. super.move(distanceInMeters);
  13. }
  14. }
  15. class Horse extends Animal {
  16. constructor(name: string) { super(name); }
  17. public move(distanceInMeters: number = 45) {
  18. console.log("Galloping...");
  19. super.move(distanceInMeters);
  20. }
  21. }
  22. let sam = new Snake("Sammy the Python");
  23. let tom: Animal = new Horse("Tommy the Palomino");
  24. sam.move();
  25. tom.move(34);

心算一下它的运行结果,再自己试试看

public private 和 protected

  • public 修饰的属性或方法是公有的,可以在任何地方被访问到,默认所有的属性和方法都是 public
  • private 修饰的属性或方法是私有的,不能在声明它的类的外部访问
  • protected 修饰的属性或方法是受保护的,它和 private 类似,区别是它在子类中也是允许被访问的

public

public我们在上面的例子已经用到了很多了,这里就不再演示新的示例了。

private

很多时候,我们希望有的属性是无法直接存取的,这时候就可以用 private

  1. class Animal {
  2. private name: string;
  3. constructor(name: string) {
  4. this.name = name;
  5. }
  6. }
  7. let a = new Animal("Jack");

此时的name属性在外部就是无法访问的了,只要访问编译就会报错。

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

官方为我们举了个很好的例子

  1. class Animal {
  2. private name: string;
  3. constructor(theName: string) { this.name = theName; }
  4. }
  5. class Rhino extends Animal {
  6. constructor() { super("Rhino"); }
  7. }
  8. class Employee {
  9. private name: string;
  10. constructor(theName: string) { this.name = theName; }
  11. }
  12. let animal = new Animal("Goat");
  13. let rhino = new Rhino();
  14. let employee = new Employee("Bob");
  15. animal = rhino;
  16. animal = employee; // 错误: Animal 与 Employee 不兼容.

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

protected

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

  1. class Person {
  2. protected name: string;
  3. constructor(name: string) { this.name = name; }
  4. }
  5. class Employee extends Person {
  6. private department: string;
  7. constructor(name: string, department: string) {
  8. super(name);
  9. this.department = department;
  10. }
  11. public getElevatorPitch() {
  12. return `Hello, my name is ${this.name} and I work in ${this.department}.`;
  13. }
  14. }
  15. let howard = new Employee("Howard", "Sales");
  16. console.log(howard.getElevatorPitch());
  17. console.log(howard.name); // 错误

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

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

  1. class Person {
  2. protected name: string;
  3. protected constructor(theName: string) { this.name = theName; }
  4. }
  5. // Employee 能够继承 Person
  6. class Employee extends Person {
  7. private department: string;
  8. constructor(name: string, department: string) {
  9. super(name);
  10. this.department = department;
  11. }
  12. public getElevatorPitch() {
  13. return `Hello, my name is ${this.name} and I work in ${this.department}.`;
  14. }
  15. }
  16. let howard = new Employee("Howard", "Sales");
  17. let john = new Person("John"); // 错误: 'Person' 的构造函数是被保护的.

readonly

可以使用readonly关键字将属性设置为只读的。 只读属性必须在声明时或构造函数里被初始化。

  1. class Octopus {
  2. readonly name: string;
  3. constructor (theName: string) {
  4. this.name = theName;
  5. }
  6. }
  7. let dad = new Octopus("Man with the 8 strong legs");
  8. dad.name = "Man with the 3-piece suit"; // 错误! name 是只读的.

参数属性

简单举一个例子吧:

  1. class Animal {
  2. constructor(private name: string) { }
  3. move(weight: number) {
  4. console.log(`${this.name} moved ${weight}m.`);
  5. }
  6. }

或许,我们可以简单的理解为,就是将声明与赋值合到了一处了。

getter && setter

如果对es6足够熟悉的话,应该是了解es6中对于class的get 与set 的
es6中,我们是这样使用的:

  1. let _age = 4;
  2. class Animal {
  3. constructor(type){ //构造函数,对象私有的东西
  4. this.type = type;
  5. },
  6. get age(){ //属性--只读
  7. return _age;
  8. }
  9. set age(val){ //属性--可以修改
  10. if(val <8 && val > 4){
  11. _age = val //这里不可以使用this.age=val,会陷入死循环,即返回值与出入口的名字不可以一样
  12. }
  13. }
  14. eat(){//方法
  15. console.log('i can eat food')
  16. }
  17. }

可以明显的看出来,这里使用的闭包的方法,这是因为es6目前还不支持我们直接设置私有属性。

在TS中,我们一般这么写:

  1. let passcode = "secret passcode";
  2. class Employee {
  3. private FullName: string;
  4. get fullName(): string {
  5. return this.FullName;
  6. }
  7. set fullName(newName: string) {
  8. if (passcode && passcode === "secret passcode") {
  9. this.FullName = newName;
  10. } else {
  11. console.log("Error: Unauthorized update of employee!");
  12. }
  13. }
  14. }
  15. let employee = new Employee();
  16. employee.fullName = "Bob Smith";
  17. if (employee.fullName) {
  18. alert(employee.fullName);
  19. }

只带有get不带有set的存取器自动被推断为readonly。 这在从代码生成.d.ts文件时是有帮助的,因为利用这个属性的用户会看到不允许够改变它的值。

静态属性 && 静态方法

如果你了解过es6中类的静态方法的话,那么你在这里应很轻松就可以了解掌握TS中类的静态方法。
在这里不会去讲述类的静态属性和静态方法,只会介绍简单的小例子,如果不清楚类的静态方法和静态属性可以参考es6的概念。

  1. class Grid {
  2. static origin = {x: 0, y: 0};
  3. calculateDistanceFromOrigin(point: {x: number; y: number;}) {
  4. let xDist = (point.x - Grid.origin.x);
  5. let yDist = (point.y - Grid.origin.y);
  6. return Math.sqrt(xDist * xDist + yDist * yDist) / this.scale;
  7. }
  8. constructor (public scale: number) { }
  9. }
  10. let grid1 = new Grid(1.0); // 1x scale
  11. let grid2 = new Grid(5.0); // 5x scale
  12. console.log(grid1.calculateDistanceFromOrigin({x: 10, y: 10}));
  13. console.log(grid2.calculateDistanceFromOrigin({x: 10, y: 10}));

这里演示了静态属性的使用,下面将会再演示一个静态方法的使用案例,如果还是不清楚 ,我想你需要去补一补es6了。

  1. class Animal {
  2. private static say() { // static 定义静态方法
  3. console.log("i can say english");
  4. }
  5. constructor(public type: string) {
  6. this.type = type;
  7. }
  8. public eat() {
  9. Animal.say(); // 引用静态方法
  10. console.log("i can eat food");
  11. }
  12. }
  13. let dog = new Animal("dog");
  14. dog.eat();
  15. // log
  16. // i can say english
  17. // i can eat food

抽象类

  • 抽象类做为其它派生类的基类使用。
  • 它们一般不会直接被实例化。
  • 不同于接口,抽象类可以包含成员的实现细节。

    abstract关键字是用于定义抽象类和在抽象类内部定义抽象方法。

  1. abstract class Animal {
  2. constructor(public name: string) {
  3. }
  4. public printName(): void {
  5. console.log("Animal's name: " + this.name);
  6. }
  7. public abstract printAge(): void; // 必须在派生类中实现
  8. }
  9. class Dog extends Animal {
  10. constructor(public age: number) {
  11. super("er huo"); // 在派生类的构造函数中必须调用 super()
  12. this.age = age;
  13. }
  14. public printAge(): void {
  15. console.log("ten years old");
  16. }
  17. public printWeight(): void {
  18. console.log("error...");
  19. }
  20. }
  21. let lees: Animal; // 允许创建一个对抽象类型的引用
  22. lees = new Animal(); // 错误: 不能创建一个抽象类的实例
  23. lees = new Dog(10); // 允许对一个抽象子类进行实例化和赋值
  24. lees.printName();
  25. lees.printAge();
  26. lees.printWeight(); // 错误: 方法在声明的抽象类中不存在

抽象类中的抽象方法不包含具体实现并且必须在派生类中实现。 抽象方法的语法与接口方法相似。 两者都是定义方法签名但不包含方法体。 然而,抽象方法必须包含abstract关键字并且可以包含访问修饰符