在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
在TypeScript中,类似于C#的结构,即一个文件中可以存在多个类,且文件名可以任意取,我们先看一个简单的类的示例。 1 class Person { 2 private name: string; 3 private age: number; 4 5 public constructor(name:string, age:number) { 6 this.name = name; 7 this.age = age; 8 } 9 10 public talk() { 11 alert("Hi, my name is " + this.name + ", i am " + this.age.toString() + "!"); 12 } 13 } 14 15 function run() { 16 var p: Person = new Person("Li Lei", 18); 17 p.talk(); 18 } 19 20 run(); TypeScript中的类需要注意下面几个点:
类的继承在TypeScript中,如何实现类的继承呢,请看如下示例: 1 class Person 2 { 3 private name: string; 4 private age: number; 5 6 constructor(name: string, age: number) 7 { 8 this.name = name; 9 this.age = age; 10 } 11 12 talk() 13 { 14 alert("Hi, my name is " + this.name + ", i am " + this.age.toString() + "!"); 15 } 16 } 17 18 class Student extends Person 19 { 20 private school: string; 21 22 constructor(name: string, age: number, school: string) 23 { 24 super(name, age); 25 this.school = school; 26 } 27 28 talk() 29 { 30 super.talk(); 31 alert("And I`m in " + this.school + "!"); 32 } 33 } 34 35 function run() 36 { 37 var p: Person = new Student("Li Lei", 18, "English School"); 38 p.talk(); 39 } 40 41 run(); 类的继承需要注意以下几点:
getter/setter封装在TypeScript中我们可以对一个成员变量进行getter和setter的封装,如下: 1 class Person 2 { 3 private _name:string; 4 5 constructor(name: string) 6 { 7 this._name = name; 8 } 9 10 set name(value:string) {this._name = value;} 11 get name() {return this._name;} 12 13 talk() 14 { 15 alert("Hi, my name is " + this.name + "!"); 16 } 17 } 18 19 function run() 20 { 21 var p:Person = new Person(null); 22 p.name = "Li Lie"; 23 p.talk(); 24 } 25 26 run(); 静态数据和方法在TypeScript中,是可以使用Static来定义静态变量及静态函数的,我们以单例类为例来看看: 1 class Person 2 { 3 private static _instance:Person; 4 5 static getInstance():Person 6 { 7 if(this._instance == null) 8 { 9 this._instance = new Person(); 10 } 11 return this._instance; 12 } 13 14 talk() 15 { 16 alert("Hi, my name is Li Lie!"); 17 } 18 } 19 20 function run() 21 { 22 Person.getInstance().talk(); 23 } 24 25 run(); referenceTypeScript允许多个类在同一个文件里,但如果类与类在不同的文件,需要这种写法: 1 /// <reference path="SimpleWebSocket.ts"/> 2 class ComplexWebSocket extends SimpleWebSocket { 3 ... 4 }
|
请发表评论