js 实现封装 多态
封装与多态在 JavaScript 中的实现
封装
封装是面向对象编程的核心概念之一,通过隐藏对象的内部细节并暴露可控的接口来实现。JavaScript 可以通过闭包、构造函数、类(ES6)等方式实现封装。
闭包实现封装

function createCounter() {
let count = 0; // 私有变量
return {
increment: function() {
count++;
},
getCount: function() {
return count;
}
};
}
const counter = createCounter();
counter.increment();
console.log(counter.getCount()); // 1
console.log(counter.count); // undefined(无法直接访问私有变量)
ES6 类实现封装
class Counter {
#count = 0; // 私有字段(ES2022)
increment() {
this.#count++;
}
getCount() {
return this.#count;
}
}
const counter = new Counter();
counter.increment();
console.log(counter.getCount()); // 1
console.log(counter.#count); // 报错(私有字段不可外部访问)
多态
多态允许不同对象对同一方法调用做出不同响应。JavaScript 通过原型链和动态类型天然支持多态。

基于原型链的多态
class Animal {
makeSound() {
console.log("Some generic sound");
}
}
class Dog extends Animal {
makeSound() {
console.log("Bark");
}
}
class Cat extends Animal {
makeSound() {
console.log("Meow");
}
}
const animals = [new Animal(), new Dog(), new Cat()];
animals.forEach(animal => animal.makeSound());
// 输出:
// Some generic sound
// Bark
// Meow
接口式多态(鸭子类型) JavaScript 不检查类型而是检查行为,只要对象具有所需方法即可:
function playSound(animal) {
if (typeof animal.makeSound === 'function') {
animal.makeSound();
}
}
const dog = { makeSound: () => console.log("Woof") };
const robot = { beep: () => console.log("Beep") };
playSound(dog); // Woof
playSound(robot); // 无输出(缺少makeSound方法)
结合封装与多态的完整示例
class Shape {
#color; // 私有字段
constructor(color) {
this.#color = color;
}
getColor() {
return this.#color;
}
area() {
throw new Error("Abstract method must be implemented");
}
}
class Circle extends Shape {
#radius;
constructor(color, radius) {
super(color);
this.#radius = radius;
}
area() {
return Math.PI * this.#radius 2;
}
}
class Square extends Shape {
#side;
constructor(color, side) {
super(color);
this.#side = side;
}
area() {
return this.#side 2;
}
}
const shapes = [
new Circle("red", 5),
new Square("blue", 4)
];
shapes.forEach(shape => {
console.log(`Color: ${shape.getColor()}, Area: ${shape.area()}`);
});
// 输出:
// Color: red, Area: 78.53981633974483
// Color: blue, Area: 16
JavaScript 的动态特性使得多态不需要显式接口定义,只需对象实现相应方法即可。封装则通过闭包或现代语法(如私有字段)来实现数据保护。






