js 多态实现
多态的概念
多态是面向对象编程的核心特性之一,指同一操作作用于不同对象时产生不同行为。JavaScript 通过原型链和对象动态特性实现多态。
基于原型链的多态实现
通过原型继承实现方法重写,子类覆盖父类方法:
function Animal() {}
Animal.prototype.sound = function() {
console.log('Animal makes sound');
};
function Dog() {}
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.sound = function() {
console.log('Bark!');
};
const animal = new Animal();
const dog = new Dog();
animal.sound(); // Animal makes sound
dog.sound(); // Bark!
基于class语法的多态
ES6 class语法通过extends和super实现更清晰的多态:
class Shape {
draw() {
console.log('Drawing shape');
}
}
class Circle extends Shape {
draw() {
console.log('Drawing circle');
}
}
const shape = new Shape();
const circle = new Circle();
shape.draw(); // Drawing shape
circle.draw(); // Drawing circle
鸭子类型实现多态
JavaScript作为动态类型语言,通过"鸭子类型"实现多态,只关注对象行为而非类型:
function makeSound(animal) {
if (animal && typeof animal.sound === 'function') {
animal.sound();
}
}
const cat = {
sound: () => console.log('Meow')
};
const car = {
sound: () => console.log('Vroom')
};
makeSound(cat); // Meow
makeSound(car); // Vroom
参数多态实现
通过函数参数不同实现不同行为:
function calculateArea(shape, ...args) {
if (shape === 'circle') {
return Math.PI * args[0] 2;
} else if (shape === 'rectangle') {
return args[0] * args[1];
}
}
console.log(calculateArea('circle', 5)); // 78.53981633974483
console.log(calculateArea('rectangle', 4, 5)); // 20
多态应用建议
- 优先使用class语法实现继承多态,代码结构更清晰
- 接口多态适合需要灵活扩展的场景
- 避免过度使用鸭子类型,适当增加类型检查保证可靠性
- 复杂多态场景可考虑使用TypeScript增强类型安全







