js实现多态
实现多态的核心概念
多态是面向对象编程的三大特性之一,指同一操作作用于不同对象时产生不同的行为。JavaScript通过原型链和对象动态特性实现多态。

基于原型链的多态实现
通过原型继承实现方法重写:

function Animal() {
this.speak = function() {
console.log('Animal sound');
};
}
function Dog() {}
Dog.prototype = new Animal();
Dog.prototype.speak = function() {
console.log('Bark!');
};
const animal = new Animal();
const dog = new Dog();
animal.speak(); // 输出: Animal sound
dog.speak(); // 输出: Bark!
基于class语法的多态实现
ES6的class语法糖更清晰地实现多态:
class Animal {
speak() {
console.log('Animal sound');
}
}
class Dog extends Animal {
speak() {
console.log('Bark!');
}
}
const animals = [new Animal(), new Dog()];
animals.forEach(animal => animal.speak());
// 输出:
// Animal sound
// Bark!
鸭子类型实现多态
JavaScript的动态类型特性允许不依赖继承的多态:
function makeSound(animal) {
if (animal && typeof animal.speak === 'function') {
animal.speak();
}
}
const cat = {
speak: () => console.log('Meow')
};
const duck = {
speak: () => console.log('Quack')
};
makeSound(cat); // 输出: Meow
makeSound(duck); // 输出: Quack
多态的应用场景
- 统一接口不同实现:不同子类对同一方法的不同实现
- 插件系统:通过约定接口实现扩展
- 策略模式:运行时选择不同算法
注意事项
- 避免过度使用多态导致代码复杂度增加
- 清晰的文档说明接口约定
- 类型检查可配合TypeScript增强可靠性






