TypeScript学习笔记(三):类

时间:2023-03-09 17:08:22
TypeScript学习笔记(三):类

在TypeScript中,类似于C#的结构,即一个文件中可以存在多个类,且文件名可以任意取,我们先看一个简单的类的示例。

 class Person {
private name: string;
private age: number; public constructor(name:string, age:number) {
this.name = name;
this.age = age;
} public talk() {
alert("Hi, my name is " + this.name + ", i am " + this.age.toString() + "!");
}
} function run() {
var p: Person = new Person("Li Lei", 18);
p.talk();
} run();

TypeScript中的类需要注意下面几个点:

  • class前不用加访问控制符,所有类都是全局公开可访问的;
  • 如果类的属性和方法不加访问控制符则默认为public;
  • 1.3开始支持protected访问权限,1.3之前仅支持public及private;
  • 构造函数不是类名而是constructor;
  • 访问类的成员变量及函数都需要加this关键字;

类的继承

在TypeScript中,如何实现类的继承呢,请看如下示例:

 class Person
{
private name: string;
private age: number; constructor(name: string, age: number)
{
this.name = name;
this.age = age;
} talk()
{
alert("Hi, my name is " + this.name + ", i am " + this.age.toString() + "!");
}
} class Student extends Person
{
private school: string; constructor(name: string, age: number, school: string)
{
super(name, age);
this.school = school;
} talk()
{
super.talk();
alert("And I`m in " + this.school + "!");
}
} function run()
{
var p: Person = new Student("Li Lei", 18, "English School");
p.talk();
} run();

类的继承需要注意以下几点:

  • 继承使用extends关键字;
  • 调用父级使用super关键字;
  • 重写父级方法不需要加override关键字,直接定义一样的方法即可;
  • 父级变量可以调用到子级的方法,符合多态的概念;

getter/setter封装

在TypeScript中我们可以对一个成员变量进行getter和setter的封装,如下:

 class Person
{
private _name:string; constructor(name: string)
{
this._name = name;
} set name(value:string) {this._name = value;}
get name() {return this._name;} talk()
{
alert("Hi, my name is " + this.name + "!");
}
} function run()
{
var p:Person = new Person(null);
p.name = "Li Lie";
p.talk();
} run();

静态数据和方法

在TypeScript中,是可以使用Static来定义静态变量及静态函数的,我们以单例类为例来看看:

 class Person
{
private static _instance:Person; static getInstance():Person
{
if(this._instance == null)
{
this._instance = new Person();
}
return this._instance;
} talk()
{
alert("Hi, my name is Li Lie!");
}
} function run()
{
Person.getInstance().talk();
} run();

reference

TypeScript允许多个类在同一个文件里,但如果类与类在不同的文件,需要这种写法:

 /// <reference path="SimpleWebSocket.ts"/>
class ComplexWebSocket extends SimpleWebSocket {
...
}