js多态实现的三种形式
多态的基本概念
多态是面向对象编程的核心特性之一,允许不同对象对同一消息(方法调用)作出不同响应。JavaScript通过动态类型和原型链实现多态,常见形式包括:
基于原型链的多态
通过原型继承实现方法的重写,子类覆盖父类方法:
function Animal() {}
Animal.prototype.sound = function() { return "Generic sound"; };
function Dog() {}
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.sound = function() { return "Bark"; };
const dog = new Dog();
console.log(dog.sound()); // 输出 "Bark"
基于对象字面量的多态
直接通过对象属性实现不同行为,无需类继承:
const bird = {
sound: function() { return "Chirp"; }
};
const cat = {
sound: function() { return "Meow"; }
};
function makeSound(animal) {
console.log(animal.sound());
}
makeSound(bird); // 输出 "Chirp"
makeSound(cat); // 输出 "Meow"
基于函数参数的多态
利用函数参数动态调用不同实现:
function calculate(operation, a, b) {
return operation(a, b);
}
const add = (x, y) => x + y;
const multiply = (x, y) => x * y;
console.log(calculate(add, 2, 3)); // 输出 5
console.log(calculate(multiply, 2, 3)); // 输出 6
关键区别
- 原型链多态:依赖继承关系,适合需要复用父类逻辑的场景。
- 对象字面量多态:灵活轻量,适合小型对象或组合模式。
- 函数参数多态:通过高阶函数实现,常见于函数式编程。
根据具体需求选择合适形式,原型链适合复杂继承结构,对象字面量和函数参数更适合松耦合设计。





