一、 类
class Greeter {
greeting: string;
constructor(message: string) {
this.greeting = message;
}
greet() {
return "Hello, " + this.greeting;
}
}
let greeter = new Greeter("world");
console.log(greeter.greet())
构造方法是 constructor
二、继承
class Animal {
move(distanceInMeters: number = 0) {
console.log(`Animal moved ${distanceInMeters}m.`);
}
}
class Dog extends Animal {
bark() {
console.log('Woof! Woof!');
}
}
const dog = new Dog();
dog.bark();
dog.move(10);
dog.bark();
super
如果父类的构造函数带参数,则子类调用父类构造函数时
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)
在构造函数里访问 this
的属性之前,我们 一定要调用 super()
三、修饰符
public
在TypeScript里,成员都默认为 public
private
不能在声明它的类的外部访问
class Animal {
private name: string;
constructor(theName: string) { this.name = theName; }
}
new Animal("Cat").name; //报错
protected
也不能在声明它的类的外部访问,但是可以在派生类中使用
class Animal {
protected name: string;
constructor(theName: string) { this.name = theName; }
}
class E extends Animal{
//继承了父类name
constructor(name: string) {super(name)}
f(){ return 'f:'+this.name; }
}
let ee=new E('tom');
console.log(ee.f())
readonly
只读属性只能在声明时,或者构造函数里被初始化
class Octopus {
readonly name: string;
readonly numberOfLegs: number = 8;
constructor (theName: string) {
this.name = theName;
}
}
let dad = new Octopus("Man with the 8 strong legs");
dad.name = "Man with the 3-piece suit"; // 错误! name 是只读的.
四、get set
class A {
//
private _n: number = 3;
constructor(nn: number) { this.n = nn }
//get属性
get n() {
return this._n;
}
//set属性
set n(x: number) {
if (x < 10) {
this.n = x;
} else {
console.log('不能大于10');
}
}
}
let a = new A(20);
五、静态属性
class A {
//
static n: number = 3;
}
console.log(A.n)
六、抽象类
抽象类不直接实例化,
abstract class A {
//抽象方法
abstract f1(): void;
//普通方法
f(): void { console.log('aa') }
}
class B extends A{
//必须要实现父类的抽象类
f1(){}
}