TypeScript学习笔记4:类
一、类的属性
public 公有(你保管的大家的东西)
private 私有,不能在声明它的类的外部访问,只能在类内部访问(就是你的物品,谁都别碰)
protect 保护,不能在声明它的类的外部访问,但继承者除外(就是你的物品,但除你的继承者外,谁都别碰)
readonly 只读属性,必须在声明时或构造函数里被初始化。
static静态属性,无需实例化就可以访问静态成员
class Grid {
static origin = {x: 0, y: 0};
calculateDistanceFromOrigin(point: {x: number; y: number;}) {
let xDist = (point.x - Grid.origin.x);
let yDist = (point.y - Grid.origin.y);
return Math.sqrt(xDist * xDist + yDist * yDist) / this.scale;
}
constructor (public scale: number) { }
}
let grid1 = new Grid(1.0); // 1x scale
let grid2 = new Grid(5.0); // 5x scale
console.log(grid1.calculateDistanceFromOrigin({x: 10, y: 10}));
console.log(grid2.calculateDistanceFromOrigin({x: 10, y: 10}));
super()方法,它会执行基类的构造方法。
二、类的存取器,set和get
let passcode = "secret passcode";
class Employee {
private _fullName: string;
get fullName(): string {
return this._fullName;
}
set fullName(newName: string) {
if (passcode && passcode == "secret passcode") {
this._fullName = newName;
}
else {
console.log("Error: Unauthorized update of employee!");
}
}
}
let employee = new Employee();
employee.fullName = "Bob Smith";
if (employee.fullName) {
alert(employee.fullName);
}
三、类的继承
class Animal {
name:string;
constructor(theName: string) { this.name = theName; }
move(distanceInMeters: number = 0) {
console.log(`${this.name} moved ${distanceInMeters}m.`);
}
}
class Snake extends Animal {
constructor(name: string) { super(name); }
move(distanceInMeters = 5) {
console.log("Slithering...");
super.move(distanceInMeters);
}
}
class Horse extends Animal {
constructor(name: string) { super(name); }
move(distanceInMeters = 45) {
console.log("Galloping...");
super.move(distanceInMeters);
}
}
let sam = new Snake("Sammy the Python");
let tom: Animal = new Horse("Tommy the Palomino");
sam.move();
tom.move(34);
四、抽象类:abstract,派生类的基类使用。它们一般不会直接被实例化。
abstract class Department{
constructor(public name:string){}
printName():void{
console.log('Department name:'+this.name);
}
abstract printMeeting():void;//抽象类中的抽象方法不包含具体实现并且必须在派生类中实现。
}
class AcountingDepartment extends Department{
constructor(){
super('Accounting and Auditing');
}
printMeeting():void{
console.log('The Accounting Department meets each Monday at 10am.');
}
generateReports():void{
console.log('Generating accounting reports...');
}
}
let department:Department;
department=new Department() //error
let department=new AcountingDepartment();
department.printName();
department.printMeeting();
//department.generateReports();
下一篇:原生js监听键盘上下键事件实例
文章
总共 0 条评论