TypeScript 类

TypeScript 是面向对象的 JavaScript。

类描述了所创建的对象共同的属性和方法。

TypeScript 支持面向对象的所有特性,比如 类、接口等。

TypeScript 类定义方式如下:

class class_name { 
    // 类作用域
}

定义类的关键字为 class,后面紧跟类名,类可以包含以下几个模块(类的数据成员):

  • 字段 − 字段是类里面声明的变量。字段表示对象的有关数据。

  • 构造函数 − 类实例化时调用,可以为类的对象分配内存。

  • 方法 − 方法为对象要执行的操作。

实例

创建一个 Person 类:

TypeScript

classPerson{}

编译以上代码,得到以下 JavaScript 代码:

JavaScript

varPerson = /** @class */(function(){functionPerson(){}returnPerson; }());

创建类的数据成员

以下实例我们声明了类 Car,包含字段为 engine,构造函数在类实例化后初始化字段 engine。

this 关键字表示当前类实例化的对象。注意构造函数的参数名与字段名相同,this.engine 表示类的字段。

此外我们也在类中定义了一个方法 disp()。

TypeScript

classCar{// 字段 engine:string; // 构造函数 constructor(engine:string){this.engine = engine}// 方法 disp():void{console.log("发动机为 : "+this.engine)}}

编译以上代码,得到以下 JavaScript 代码:

JavaScript

varCar = /** @class */(function(){// 构造函数 functionCar(engine){this.engine = engine; }// 方法 Car.prototype.disp = function(){console.log("发动机为 : " + this.engine); }; returnCar; }());

创建实例化对象

我们使用 new 关键字来实例化类的对象,语法格式如下:

var object_name = new class_name([ arguments ])

类实例化时会调用构造函数,例如:

var obj = new Car("Engine 1")

类中的字段属性和方法可以使用 . 号来访问:

// 访问属性
obj.field_name 

// 访问方法
obj.function_name()

完整实例

以下实例创建来一个 Car 类,然后通过关键字 new 来创建一个对象并访问属性和方法:

TypeScript

classCar{// 字段engine:string; // 构造函数constructor(engine:string){this.engine = engine}// 方法disp():void{console.log("函数中显示发动机型号 : "+this.engine)}}// 创建一个对象varobj = newCar("XXSY1")// 访问字段console.log("读取发动机型号 : "+obj.engine)// 访问方法obj.disp()

编译以上代码,得到以下 JavaScript 代码:

JavaScript

varCar = /** @class */(function(){// 构造函数functionCar(engine){this.engine = engine; }// 方法Car.prototype.disp = function(){console.log("函数中显示发动机型号 : " + this.engine); }; returnCar; }()); // 创建一个对象varobj = newCar("XXSY1"); // 访问字段console.log("读取发动机型号 : " + obj.engine); // 访问方法obj.disp();

输出结果为:

读取发动机型号 :  XXSY1
函数中显示发动机型号  :   XXSY1

类的继承

TypeScript 支持继承类,即我们可以在创建类的时候继承一个已存在的类,这个已存在的类称为父类,继承它的类称为子类。

类继承使用关键字 extends,子类除了不能继承父类的私有成员(方法和属性)和构造函数,其他的都可以继承。

TypeScript 一次只能继承一个类,不支持继承多个类,但 TypeScript 支持多重继承(A 继承 B,B 继承 C)。

语法格式如下:

class child_class_name extends parent_class_name

实例

类的继承:实例中创建了 Shape 类,Circle 类继承了 Shape 类,Circle 类可以直接使用 Area 属性:

TypeScript

classShape{Area:numberconstructor(a:number){this.Area = a}}classCircleextendsShape{disp():void{console.log("圆的面积: "+this.Area)}}varobj = newCircle(223); obj.disp()

编译以上代码,得到以下 JavaScript 代码:

JavaScript

var__extends = (this && this.__extends) || (function(){varextendStatics = function(d, b){extendStatics = Object.setPrototypeOf || ({__proto__: []}instanceofArray && function(d, b){d.__proto__ = b; }) || function(d, b){for(varpinb)if(b.hasOwnProperty(p))d[p] = b[p]; }; returnextendStatics(d, b); }; returnfunction(d, b){extendStatics(d, b); function__(){this.constructor = d; }d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new__()); }; })(); varShape = /** @class */(function(){functionShape(a){this.Area = a; }returnShape; }()); varCircle = /** @class */(function(_super){__extends(Circle, _super); functionCircle(){return_super !== null && _super.apply(this, arguments) || this; }Circle.prototype.disp = function(){console.log("圆的面积: " + this.Area); }; returnCircle; }(Shape)); varobj = newCircle(223); obj.disp();

输出结果为:

圆的面积:  223

需要注意的是子类只能继承一个父类,TypeScript 不支持继承多个类,但支持多重继承,如下实例:

TypeScript

classRoot{str:string; }classChildextendsRoot{}classLeafextendsChild{}// 多重继承,继承了 Child 和 Root 类varobj = newLeaf(); obj.str ="hello"console.log(obj.str)

编译以上代码,得到以下 JavaScript 代码:

JavaScript

var__extends = (this && this.__extends) || (function(){varextendStatics = function(d, b){extendStatics = Object.setPrototypeOf || ({__proto__: []}instanceofArray && function(d, b){d.__proto__ = b; }) || function(d, b){for(varpinb)if(b.hasOwnProperty(p))d[p] = b[p]; }; returnextendStatics(d, b); }; returnfunction(d, b){extendStatics(d, b); function__(){this.constructor = d; }d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new__()); }; })(); varRoot = /** @class */(function(){functionRoot(){}returnRoot; }()); varChild = /** @class */(function(_super){__extends(Child, _super); functionChild(){return_super !== null && _super.apply(this, arguments) || this; }returnChild; }(Root)); varLeaf = /** @class */(function(_super){__extends(Leaf, _super); functionLeaf(){return_super !== null && _super.apply(this, arguments) || this; }returnLeaf; }(Child)); // 多重继承,继承了 Child 和 Root 类varobj = newLeaf(); obj.str = "hello"; console.log(obj.str);

输出结果为:

hello

继承类的方法重写

类继承后,子类可以对父类的方法重新定义,这个过程称之为方法的重写。

其中 super 关键字是对父类的直接引用,该关键字可以引用父类的属性和方法。

TypeScript

classPrinterClass{doPrint():void{console.log("父类的 doPrint() 方法。")}}classStringPrinterextendsPrinterClass{doPrint():void{super.doPrint()// 调用父类的函数console.log("子类的 doPrint()方法。")}}

编译以上代码,得到以下 JavaScript 代码:

JavaScript

varobj = newStringPrinter()obj.doPrint()var__extends = (this && this.__extends) || (function(){varextendStatics = function(d, b){extendStatics = Object.setPrototypeOf || ({__proto__: []}instanceofArray && function(d, b){d.__proto__ = b; }) || function(d, b){for(varpinb)if(b.hasOwnProperty(p))d[p] = b[p]; }; returnextendStatics(d, b); }; returnfunction(d, b){extendStatics(d, b); function__(){this.constructor = d; }d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new__()); }; })(); varPrinterClass = /** @class */(function(){functionPrinterClass(){}PrinterClass.prototype.doPrint = function(){console.log("父类的 doPrint() 方法。"); }; returnPrinterClass; }()); varStringPrinter = /** @class */(function(_super){__extends(StringPrinter, _super); functionStringPrinter(){return_super !== null && _super.apply(this, arguments) || this; }StringPrinter.prototype.doPrint = function(){_super.prototype.doPrint.call(this); // 调用父类的函数console.log