TypeScript - 类

TypeScript是面向对象的JavaScript. TypeScript支持面向对象的编程功能,如类,接口等.OOP方面的类是创建对象的蓝图.类封装了对象的数据. Typescript为这个名为class的概念提供内置支持. JavaScript ES5或更早版本不支持类. Typescript从ES6获得此功能.

创建类

使用class关键字在TypeScript中声明一个类.相同的语法在下面给出 :

语法

class class_name { 
   //class scope 
}

class关键字后跟类名.在命名类时必须考虑标识符的规则.

类定义可以包括以下 :

  • 字段 : 字段是类中声明的任何变量.字段表示与对象有关的数据

  • 构造函数 : 负责为班级对象分配内存

  • 功能 : 函数表示对象可以采取的操作.它们有时也被称为方法

这些组件放在一起被称为类的数据成员.

考虑打字稿中的类人物.

 
 class Person {
}

在编译时,它将生成以下JavaScript代码.

//Generated by typescript 1.8.10
var Person = (function () {
   function Person() {
   }
   return Person;
}());

示例:声明一个类

class Car { 
   //field 
   engine:string; 
 
   //constructor 
   constructor(engine:string) { 
      this.engine = engine 
   }  

   //function 
   disp():void { 
      console.log("Engine is  :   "+this.engine) 
   } 
}

该示例声明了一个类Car.该类有一个名为engine的字段.声明字段时不使用 var 关键字.上面的例子声明了类的构造函数.

构造函数是类的一个特殊函数,负责初始化类的变量. TypeScript使用constructor关键字定义构造函数.构造函数是一个函数,因此可以参数化.

this 关键字引用类的当前实例.这里,参数名称和类字段的名称是相同的.因此,为了避免歧义,类的字段以 this 关键字为前缀.

disp()是一个简单的函数定义.请注意,这里不使用function关键字.

在编译时,它将生成以下JavaScript代码.

//Generated by typescript 1.8.10
var Car = (function () {
   //constructor
   function Car(engine) {
      this.engine = engine;
   }
	
   //function
   Car.prototype.disp = function () {
      console.log("Engine is  :   " + this.engine);
   };
   return Car;
}());

创建实例对象

要创建类的实例,请使用 new 关键字后跟类名.相同的语法在下面给出 :

语法

 
 var object_name = new class_name([参数])

  • new 关键字负责实例化.

  • 表达式的右侧调用构造函数.如果参数化了构造函数,则应该传递值.

示例:实例化类

 
 var obj = new Car("Engine 1")

访问属性和函数

可以通过对象访问类的属性和函数.使用 ' . '点符号(称为句点)来访问类的数据成员.

 
//访问属性
 obj. field_name 
//访问函数
 obj.function_name()

示例:将它们放在一起

class Car { 
   //field 
   engine:string; 
   
   //constructor 
   constructor(engine:string) { 
      this.engine = engine 
   }  
   
   //function 
   disp():void { 
      console.log("Function displays Engine is  :   "+this.engine) 
   } 
} 

//create an object 
var obj = new Car("XXSY1")

//access the field 
console.log("Reading attribute value Engine as :  "+obj.engine)  

//access the function
obj.disp()

在编译时,它将生成以下JavaScript代码.

//Generated by typescript 1.8.10
var Car = (function () {
   //constructor
   function Car(engine) {
      this.engine = engine;
   }
	
   //function
   Car.prototype.disp = function () {
      console.log("Function displays Engine is  :   " + this.engine);
   };
   return Car;
}());

//create an object
var obj = new Car("XXSY1");

//access the field
console.log("Reading attribute value Engine as :  " + obj.engine);

//access the function
obj.disp();
The output of the above code is as follows −
Reading attribute value Engine as :  XXSY1 
Function displays Engine is  :   XXSY1

上述代码的输出如下 :

Reading attribute value Engine as :  XXSY1 
Function displays Engine is  :   XXSY1

类继承

TypeScript支持继承的概念.继承是程序从现有类创建新类的能力.扩展为创建较新类的类称为父类/超类.新创建的类称为子/子类.

一个类使用'extends'关键字从另一个类继承.子类继承除父类的私有成员和构造函数之外的所有属性和方法.

语法

class child_class_name extends parent_class_name

但是,TypeScript不支持多重继承.

示例:类继承

class Shape { 
   Area:number 
   
   constructor(a:number) { 
      this.Area = a 
   } 
} 

class Circle extends Shape { 
   disp():void { 
      console.log("Area of the circle:  "+this.Area) 
   } 
}
  
var obj = new Circle(223); 
obj.disp()

在编译时,它将生成以下JavaScript代码.

//Generated by typescript 1.8.10
var __extends = (this && this.__extends) || function (d, b) {
   for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
   function __() { this.constructor = d; }
   d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Shape = (function () {
   function Shape(a) {
      this.Area = a;
   }
   return Shape;
}());

var Circle = (function (_super) {
   __extends(Circle, _super);
   function Circle() {
      _super.apply(this, arguments);
   }
	
   Circle.prototype.disp = function () { 
      console.log("Area of the circle:  " + this.Area); 
   };
   return Circle;
}(Shape));

var obj = new Circle(223);
obj.disp();

上述代码的输出如下 :

Area of the Circle: 223

上面的例子声明了一个类Shape.该类由Circle类扩展.由于类之间存在继承关系,因此子类(即Car类)可以隐式访问其父类属性,即区域.

继承可以归类为 :

  • 单身 : 每个班级最多可以从一个父班级延伸

  • 多个 : 一个类可以从多个类继承. TypeScript不支持多重继承.

  • 多级 : 以下示例显示了多级继承的工作原理.

示例

class Root { 
   str:string; 
} 

class Child extends Root {} 
class Leaf extends Child {} //indirectly inherits from Root by virtue of inheritance  

var obj = new Leaf(); 
obj.str ="hello" 
console.log(obj.str)

Leaf类从Root派生属性子类通过多级继承.

在编译时,它将生成以下JavaScript代码.

//Generated by typescript 1.8.10
var __extends = (this && this.__extends) || function (d, b) {
   for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
   function __() { this.constructor = d; }
   d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};

var Root = (function () {
   function Root() {
   }
   return Root;
}());

var Child = (function (_super) {
   __extends(Child, _super);
   function Child() {
      _super.apply(this, arguments);
   }
   return Child;
}(Root));

var Leaf = (function (_super) {
   __extends(Leaf, _super);
   function Leaf() {
      _super.apply(this, arguments);
   }
   return Leaf;
}(Child));

var obj = new Leaf();
obj.str = "hello";
console.log(obj.str);

其输出如下 :

输出

hello

TypeScript─类继承和方法覆盖

方法覆盖是一种机制子类重新定义了超类的方法.以下示例说明了相同 :

class PrinterClass { 
   doPrint():void {
      console.log("doPrint() from Parent called…") 
   } 
} 

class StringPrinter extends PrinterClass { 
   doPrint():void { 
      super.doPrint() 
      console.log("doPrint() is printing a string…")
   } 
} 

var obj = new StringPrinter() 
obj.doPrint()

super关键字用于指代类的直接父级.关键字可用于引用变量,属性或方法的超类版本.第13行调用doWork()函数的超类版本.

在编译时,它将生成以下JavaScript代码.

//Generated by typescript 1.8.10
var __extends = (this && this.__extends) || function (d, b) {
   for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
   function __() { this.constructor = d; }
   d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};

var PrinterClass = (function () {
   function PrinterClass() {
   }
   PrinterClass.prototype.doPrint = function () { 
      console.log("doPrint() from Parent called…"); 
   };
   return PrinterClass;
}());

var StringPrinter = (function (_super) {
   __extends(StringPrinter, _super);
	
   function StringPrinter() {
      _super.apply(this, arguments);
   }
	
   StringPrinter.prototype.doPrint = function () {
      _super.prototype.doPrint.call(this);
      console.log("doPrint() is printing a string…");
   };
	
   return StringPrinter;
}(PrinterClass));

var obj = new StringPrinter();
obj.doPrint();

上述代码的输出如下 :

doPrint() from Parent called… 
doPrint() is printing a string…

静态关键字

static关键字可以应用于类的数据成员.静态变量保留其值,直到程序完成执行.静态成员由类名引用.

示例

class StaticMem {  
   static num:number; 
   
   static disp():void { 
      console.log("The value of num is"+ StaticMem.num) 
   } 
} 

StaticMem.num = 12     // initialize the static variable 
StaticMem.disp()      // invoke the static method

编译时,它将生成以下JavaScript代码.

//Generated by typescript 1.8.10
var StaticMem = (function () {
   function StaticMem() {
   }
	
   StaticMem.disp = function () {
      console.log("The value of num is" + StaticMem.num);
   };
	
   return StaticMem;
}());

StaticMem.num = 12;     // initialize the static variable
StaticMem.disp();      // invoke the static method

上述代码的输出如下 :

The value of num is 12

instanceof运算符

instanceof <如果对象属于指定的类型,则运算符返回true.

示例

class Person{ } 
var obj = new Person() 
var isPerson = obj instanceof Person; 
console.log(" obj is an instance of Person " + isPerson);

在编译时,它将生成以下JavaScript代码.

//Generated by typescript 1.8.10
var Person = (function () {
   function Person() {
   }
   return Person;
}());

var obj = new Person();
var isPerson = obj instanceof Person;
console.log(" obj is an instance of Person " + isPerson);

上述代码的输出如下 :

obj is an instance of Person True

数据隐藏

类可以控制其数据成员对成员的可见性其他课程.此功能称为数据隐藏或封装.

Object Orientation使用访问修饰符或访问说明符的概念来实现Encapsulation的概念.访问说明符/修饰符定义类定义类之外的类数据成员的可见性.

TypeScript支持的访问修饰符是 :

S.No.Access Specifier&说明
1.

public

公共数据成员具有通用可访问性.默认情况下,类中的数据成员是公共的.

2.

private

私人数据成员只能在定义这些成员的类中访问.如果外部类成员尝试访问私有成员,则编译器会抛出错误.

3.

protected

受保护的数据成员可由同一成员访问类是前者的类,也是子类的成员.

示例

现在让我们举一个例子来看看数据隐藏的工作原理 :

 
 class Encapsulate {
 str:string ="hello"
 private str2:string ="world"
} 
 var obj = new Encapsulate()
 console.log(obj. str)//accessible 
 console.log(obj.str2)//编译错误,因为str2是私有的

该类有两个字符串属性, str1和str2,分别是公共成员和私有成员.该类被实例化.该示例返回编译时错误,因为私有属性str2在声明它的类之外被访问.

类和接口

类也可以实现接口.

 
 interface ILoan {
 interest:number 
} 
 class AgriLoan实现ILoan {
利息:数字
回扣:数字
构造函数(利息:数字,回扣:数字){
 this.interest = interest 
 this .rebate =回扣
} 
} 
 var obj = new AgriLoan(10,1)
 console.log("兴趣是:"+ obj.interest +"回扣是:"+ obj.rebate"

AgriLoan类实现了贷款接口.因此,它现在绑定在类上以包含属性 interest 作为其成员.

在编译时,它将生成以下JavaScript代码.

interface ILoan { 
   interest:number 
} 

class AgriLoan implements ILoan { 
   interest:number 
   rebate:number 
   
   constructor(interest:number,rebate:number) { 
      this.interest = interest 
      this.rebate = rebate 
   } 
} 

var obj = new AgriLoan(10,1) 
console.log("Interest is : "+obj.interest+" Rebate is : "+obj.rebate )

上述代码的输出如下 :

Interest is : 10 Rebate is : 1