TypeScript-类

TypeScript是面向对象的JavaScript。TypeScript支持面向对象的编程功能,例如类,接口等。就OOP而言,类是用于创建对象的蓝图。一个类封装对象的数据。Typescript对此类的概念提供了内置支持。JavaScript ES5或更早版本不支持类。Typescript从ES6获得此功能。

建立Class类

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

语法

class class_name { 
   //class scope 
}

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

类定义可以包括以下内容-

  • 字段-字段是在类中声明的任何变量。字段代表与对象有关的数据
  • 构造函数-负责为类的对象分配内存
  • 功能-功能代表对象可以采取的行动。它们有时也称为方法

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

考虑typescript中的类Person。

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的字段。该变种而声明一个字段的关键字不被使用。上面的示例声明了该类的构造函数。

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

这个关键字指向类的当前实例。此处,参数名称和类字段的名称相同。因此,为避免歧义,类的字段以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([ arguments ])
  • 新的关键字负责实例化。
  • 表达式的右侧调用构造函数。如果构造函数已参数化,则应传递值。

示例:实例化一个类

var obj = new Car("Engine 1")

访问属性和功能

可以通过对象访问类的属性和函数。使用 ‘ 。点表示法(称为句点),用于访问类的数据成员。

//accessing an attribute 
obj.field_name 

//accessing a function 
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();

上面代码的输出如下-

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)可以隐式访问其父类属性(即area)。

继承可以分类为-

  • Single– 每个Class类级最多只能从一个父Class类级扩展
  • Multiple– 一个类可以从多个类继承。TypeScript不支持多重继承。
  • Multi-level– 以下示例显示了多级继承的工作方式。

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和Child类派生属性。

编译时,它将生成以下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如果对象属于指定型操作者返回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 

资料隐藏

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

面向对象使用访问修饰符或访问指定符的概念来实现封装的概念。访问说明符/修饰符定义类的数据成员在其定义类之外的可见性。

TypeScript支持的访问修饰符为-

序号访问说明和描述
1public
公共数据成员具有普遍可访问性。默认情况下,类中的数据成员是公共的。
2private
私有数据成员只能在定义这些成员的类中访问。如果外部类成员尝试访问私有成员,则编译器将引发错误。
3protected
与前者相同的类中的成员以及子类的成员都可以访问受保护的数据成员。

现在让我们以一个示例来看数据隐藏如何工作-

class Encapsulate { 
   str:string = "hello" 
   private str2:string = "world" 
}
 
var obj = new Encapsulate() 
console.log(obj.str)     //accessible 
console.log(obj.str2)   //compilation Error as str2 is private

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

类和接口

类也可以实现接口。

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 )

AgriLoan类实现接口Loan。因此,它现在绑定到类上,以将财产权益作为其成员。

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

//Generated by typescript 1.8.10
var AgriLoan = (function () {
   function AgriLoan(interest, rebate) {
      this.interest = interest;
      this.rebate = rebate;
   }
   return AgriLoan;
}());

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

上面代码的输出如下-

Interest is : 10 Rebate is : 1

觉得文章有用?

点个广告表达一下你的爱意吧 !😁