类的封装
eat方法可以直接调用去实现一个功能, 但是你不需要知道eat里面具体怎么去实现
class Animal {
name: string;
constructor(name: string) {
this.name = name;
}
eat(food: string) {
console.log(this.name, "is eating ", food);
}
}
类的继承
Dog类继承自Animal类, 所以dog实例会拥有Animal类的所有属性和方法
class Dog extends Animal {
constructor(name: string) {
// 派生类的构造函数必须包含 "super" 调用。
super(name);
}
}
类的多态
Dog类和Cat都继承自Animal类, 所以都有eat方法, 但是Cat对eat方法进行了重载, 所以在调用eat方法时, 会有不同的表现, 这就叫类的多态
class Cat extends Animal {
eat() {
console.log("I don't wanna eat!");
}
}
const dog = new Dog("dog");
const cat = new Cat("dog");
dog.eat("bread");
cat.eat();
静态属性
class Bear extends Animal {
static shape: string = "round";
static bite() {
console.log("I will bite you!");
}
}
console.log(Bear.shape);
Bear.bite();
typescript的修饰符
public外部可读(这个是默认的)
private仅限内部可读(调用)
protected
private和protected的异同
相同点: private和protected修饰的方法或属性都无法通过外部访问或调用
不同点: private修饰的属性或方法不可以在子类中通过super.属性名或者super.方法名拿到, 但是protected修饰的方法或属性可以
class People {
private name: string;
protected age: number = 17;
constructor(name: string, age: number) {
this.name = name;
}
eat(food: string) {
console.log(`${this.name} is ear ${food}`);
}
}
class Women extends People {
run() {
console.log(this.age);
this.eat("orange");
}
}
class TallWomen extends Women {
fight() {
console.log(this.age);
}
}
const xiaoMing = new People("Mr.Ming", 18);
// xiaoMing.eat("rice");
// console.log(xiaoMing.name);
// console.log(xiaoMing.age);
const xiaoMei = new Women("Mrs.Mei", 20);
xiaoMei.run();
const mary = new TallWomen("Mary", 27);
mary.fight();