js 实现多态
多态的概念
多态是面向对象编程的核心特性之一,指同一操作作用于不同对象时会产生不同的行为。JavaScript 通过原型链和动态类型实现多态,无需像传统语言(如 Java)那样依赖严格的类继承体系。
基于原型链的多态实现
JavaScript 通过原型链实现继承,子类可以重写父类方法以实现多态行为:

function Animal(name) {
this.name = name;
}
Animal.prototype.speak = function() {
console.log(this.name + ' makes a noise.');
};
function Dog(name) {
Animal.call(this, name);
}
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
// 重写父类方法
Dog.prototype.speak = function() {
console.log(this.name + ' barks.');
};
const animal = new Animal('Generic Animal');
const dog = new Dog('Buddy');
animal.speak(); // 输出: "Generic Animal makes a noise."
dog.speak(); // 输出: "Buddy barks."
基于接口的多态模拟
JavaScript 没有接口的语法,但可以通过约定实现类似效果:

class Shape {
area() {
throw new Error('Method "area()" must be implemented.');
}
}
class Circle extends Shape {
constructor(radius) {
super();
this.radius = radius;
}
area() {
return Math.PI * this.radius 2;
}
}
class Square extends Shape {
constructor(side) {
super();
this.side = side;
}
area() {
return this.side 2;
}
}
const shapes = [new Circle(2), new Square(5)];
shapes.forEach(shape => console.log(shape.area()));
鸭子类型实现多态
JavaScript 的动态类型系统允许通过"鸭子类型"(Duck Typing)实现多态,只需对象具有所需方法即可:
function logSound(animal) {
if (typeof animal.makeSound === 'function') {
animal.makeSound();
}
}
const dog = {
makeSound: () => console.log('Woof!')
};
const cat = {
makeSound: () => console.log('Meow!')
};
logSound(dog); // 输出: "Woof!"
logSound(cat); // 输出: "Meow!"
使用 Symbol 实现多态
ES6 的 Symbol 可以创建唯一的方法名,避免属性名冲突:
const speak = Symbol('speak');
class Bird {
[speak]() {
console.log('Chirp!');
}
}
class Parrot extends Bird {
[speak]() {
console.log('Polly wants a cracker!');
}
}
const bird = new Bird();
const parrot = new Parrot();
bird[speak](); // 输出: "Chirp!"
parrot[speak](); // 输出: "Polly wants a cracker!"
多态的应用场景
- 插件系统:不同插件实现相同接口但行为不同
- UI 组件:不同组件响应相同事件但表现不同
- 数据处理:不同数据源实现相同解析接口
- 游戏开发:不同角色对同一指令做出不同反应
JavaScript 的多态实现更加灵活,不需要严格的类型系统,通过检查对象是否具有特定方法或属性即可实现多态行为。这种动态特性使得代码更具扩展性和适应性。






