js 多态的实现
JavaScript 多态的实现方式
JavaScript 的多态主要通过原型链、类继承和接口模拟实现。以下是具体实现方法:
基于原型链的多态
通过原型链实现方法的重写,子类可以覆盖父类的方法:

function Animal() {}
Animal.prototype.sound = function() {
console.log("Animal makes a sound");
};
function Dog() {}
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.sound = function() {
console.log("Dog barks");
};
const animal = new Animal();
const dog = new Dog();
animal.sound(); // 输出: Animal makes a sound
dog.sound(); // 输出: Dog barks
基于 ES6 Class 的多态
使用 class 和 extends 实现方法重写:

class Animal {
sound() {
console.log("Animal makes a sound");
}
}
class Dog extends Animal {
sound() {
console.log("Dog barks");
}
}
const animal = new Animal();
const dog = new Dog();
animal.sound(); // 输出: Animal makes a sound
dog.sound(); // 输出: Dog barks
基于鸭子类型的多态
JavaScript 是动态类型语言,通过检查对象是否实现特定方法来实现多态:
function makeSound(animal) {
if (animal.sound && typeof animal.sound === 'function') {
animal.sound();
}
}
const cat = { sound: () => console.log("Meow") };
const car = { honk: () => console.log("Beep") };
makeSound(cat); // 输出: Meow
makeSound(car); // 无输出(未实现 sound 方法)
通过策略模式实现多态
将行为封装为策略对象,动态切换:
const soundStrategies = {
dog: () => console.log("Bark"),
cat: () => console.log("Meow")
};
function Animal(strategy) {
this.sound = soundStrategies[strategy];
}
const dog = new Animal('dog');
const cat = new Animal('cat');
dog.sound(); // 输出: Bark
cat.sound(); // 输出: Meow
关键点总结
- 原型链:通过修改原型对象实现方法覆盖。
- ES6 Class:语法糖,本质仍是原型继承。
- 鸭子类型:关注对象的能力而非类型。
- 策略模式:将行为解耦为独立对象。
多态在 JavaScript 中更倾向于“行为多态”,而非严格的类型系统多态。






