【延伸学习】TS(JS)类的继承(prototype、call、apply,extends)
// 基类
class Animal {
name: string;
constructor(name: string) {
this.name = name;
}
move(distanceInMeters: number = 0) {
console.log(`${this.name} moved ${distanceInMeters}m.`);
}
}
// 继承自Animal的子类
class Dog extends Animal {
bark() {
console.log('Woof!');
}
}
// 使用prototype属性实现继承
function Animal() {
this.name = 'Animal';
}
Animal.prototype.move = function(distanceInMeters: number) {
console.log(`${this.name} moved ${distanceInMeters}m.`);
};
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
const dog = new Dog();
dog.name = 'Buddy';
dog.bark = function() { console.log('Woof!'); };
dog.move(10);
// 使用call或apply调用父类构造函数
class Cat extends Animal {
constructor(name: string) {
super.constructor.call(this, name);
}
meow() {
console.log('Meow!');
}
}
const cat = new Cat('Kitty');
cat.move(5);
// TypeScript中的extends关键字也可以用于接口继承
interface Animal {
name: string;
move: (distanceInMeters: number) => void;
}
interface Dog extends Animal {
bark: () => void;
}
// 实现接口
const dog: Dog = {
name: 'Rex',
move: (distanceInMeters = 0) => {
console.log(`${dog.name} moved ${distanceInMeters}m.`);
},
bark: () => {
console.log('Woof!');
},
};
这个代码示例展示了如何在TypeScript中使用类继承、prototype属性以及call和apply方法来实现继承。同时,也演示了如何在TypeScript中使用接口来实现多态行为。
评论已关闭