js实现多态
多态的概念
多态是面向对象编程的三大特性之一(封装、继承、多态),指同一操作作用于不同对象会产生不同的行为。在JavaScript中,由于是动态类型语言,多态主要通过原型继承和接口实现来实现。

基于原型继承的多态
JavaScript通过原型链实现继承,子类可以重写父类的方法,调用时会根据实际对象类型执行对应方法。

function Animal() {
this.sound = '...';
}
Animal.prototype.makeSound = function() {
console.log(this.sound);
};
function Dog() {
this.sound = 'Woof!';
}
Dog.prototype = Object.create(Animal.prototype);
function Cat() {
this.sound = 'Meow!';
}
Cat.prototype = Object.create(Animal.prototype);
const animals = [new Dog(), new Cat()];
animals.forEach(animal => animal.makeSound()); // 输出"Woof!"和"Meow!"
基于接口的多态
JavaScript没有接口的语法,但可以通过约定和duck typing实现类似效果。只要对象具有相同的方法名,就可以被视为实现了同一接口。
function makeSound(animal) {
if (animal && typeof animal.makeSound === 'function') {
animal.makeSound();
}
}
const dog = {
makeSound: () => console.log('Woof!')
};
const cat = {
makeSound: () => console.log('Meow!')
};
makeSound(dog); // "Woof!"
makeSound(cat); // "Meow!"
多态的应用场景
表单验证:不同类型的表单字段可以使用相同的验证接口 游戏开发:不同角色可以响应相同的动作命令 插件系统:不同插件实现相同的接口方法
实现多态的注意事项
方法名要保持一致,这是多态的基础 尽量使用鸭子类型(duck typing),关注对象能做什么而不是它是什么 在大型项目中可以使用TypeScript的interface来明确接口约定





