js多态实现
多态的概念
多态是面向对象编程的三大特性之一,指同一操作作用于不同对象时产生不同的行为。在JavaScript中,由于语言本身的动态特性,多态的实现方式与其他静态语言有所不同。
基于原型链的多态实现
JavaScript通过原型链实现继承,子类可以覆盖父类的方法实现多态:

function Animal() {}
Animal.prototype.sound = function() {
console.log("动物发出声音");
};
function Dog() {}
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.sound = function() {
console.log("汪汪汪");
};
function Cat() {}
Cat.prototype = Object.create(Animal.prototype);
Cat.prototype.sound = function() {
console.log("喵喵喵");
};
const animals = [new Animal(), new Dog(), new Cat()];
animals.forEach(animal => animal.sound());
基于ES6类的多态实现
ES6引入class语法糖后,多态实现更加清晰:
class Animal {
makeSound() {
console.log("动物发出声音");
}
}
class Dog extends Animal {
makeSound() {
console.log("汪汪汪");
}
}
class Cat extends Animal {
makeSound() {
console.log("喵喵喵");
}
}
const animals = [new Animal(), new Dog(), new Cat()];
animals.forEach(animal => animal.makeSound());
基于鸭子类型的多态
JavaScript是动态类型语言,更倾向于"鸭子类型"的多态实现:

function makeSound(animal) {
if (animal && typeof animal.sound === 'function') {
animal.sound();
}
}
const dog = {
sound: () => console.log("汪汪汪")
};
const cat = {
sound: () => console.log("喵喵喵")
};
makeSound(dog);
makeSound(cat);
多参数函数的多态实现
通过参数类型和数量的不同实现多态:
function add() {
if (arguments.length === 2) {
return arguments[0] + arguments[1];
} else if (arguments.length === 3) {
return arguments[0] + arguments[1] + arguments[2];
}
return 0;
}
console.log(add(1, 2)); // 3
console.log(add(1, 2, 3)); // 6
使用Symbol实现多态
利用Symbol唯一性实现更安全的多态:
const sound = Symbol('sound');
class Animal {
[sound]() {
console.log("动物声音");
}
}
class Dog extends Animal {
[sound]() {
console.log("汪汪汪");
}
}
const dog = new Dog();
dog[sound]();
多态的应用场景
- 插件系统设计:不同插件实现相同接口但行为不同
- UI组件库:基础组件和定制组件实现相同方法但渲染不同
- 游戏开发:不同角色对同一消息做出不同响应
- 中间件系统:不同中间件对请求处理方式不同
JavaScript的多态实现更加灵活,不需要显式接口定义,只需对象具有相应方法或属性即可实现多态行为。






