TS:ES6类的扩展
1. 公共、私有、受保护的修饰符
-
在typescript中,对ES6标准的类的成员做了扩展,即可以使用
public,private,protected,readonly
对成员进行修饰,限制其使用域。 -
理解protected与private的区别:
-
protected成员在其派生类(子类)中仍然可以访问到;
-
若将构造函数标记成protected,意味着这个类不能再包含他的类以外被实例化,但是能够被继承:
class Person { protected name : string; protected constructor(theName : string){ this.name = theName; } } // Employee 能够继承 Person class Employee extends Person { private department: string; constructor(name: string, department: string) { super(name); // 可以实现 this.department = department; } public getElevatorPitch() { return `Hello, my name is ${ this.name} and I work in ${ this.department}.`; } } let howard = new Employee("Howard", "Sales"); // ok,Employee类继承了Person,拥有自己的构造方法 let john = new Person("John"); // 错误: 'Person' 的构造函数是被保护的.
-
2. 参数属性
-
上面例子中,我们在类中定义了一个name以及一个参数为theName的构造函数,将theName赋值给name。参数属性可以将这两者合并起来;
-
参数属性通过给构造函数参数前面添加一个访问限定符来声明。
class Person { constructor(readonly name : string) { }; }
3. 存取器
-
typescript支持通过getter和setter来拦截对对象成员访问。
-
来看一个设置密码的实例:
class ID { private _password : number; get password() : number{ return this._password; } set password(oldPwd: number ,newPwd : number){ if(oldPwd && oldPwd === _password){ this._password = newPwd; }else{ console.log("Error : old password is not valid"); } } }
4. 静态属性
-
和Java一样,typescript也支持直接通过
类名.属性
来进行静态属性的访问。class Person { static proto : string = 'human'; } console.log(Person.proto); // 'human'
5. 抽象类
-
抽象类作为其他派生类的基类使用。它们一般不会被直接实例化;
-
和Java一样,抽象类的抽象方法不需要提供具体实现,但必须在派生类中实现;
abstract class Person { constructor(public name : string){ }; printName() : void { console.log('my name is ' + this.name); } abstract printMeeting() : void; // 必须在子类中实现 } class Employee extends Person{ constructor(){ super('yivi'); } printMeeting(): void{ console.log('I am Employee ' + this.name); } printReports(): void{ console.log('I am not exist'); } } let p : Person; // ok,允许创建一个对抽象类型的引用 p = new Person(); // error,不允许创建一个抽象类的实例’ p = new Employee(); // ok p.printName(); p.printMeeting(); p.printReports(); //error,方法在生命的抽象类中不存在。
6. 将类当作接口使用
-
因为类可与i创建出类型,所以我们可以在允许使用接口的地方使用类。
class Point { x : number; y : number; } interface Point3D extends Point { z : number; } let point : Point3D = { x : 1, y : 2, z : 3 }