js 实现封装 多态
封装与多态在 JavaScript 中的实现
封装
封装的核心是通过限制对对象内部状态的直接访问,仅暴露必要的接口。在 JavaScript 中可以通过闭包、模块模式或 ES6 的 class 语法实现。
闭包实现私有变量
function Counter() {
let count = 0; // 私有变量
this.increment = function() {
count++;
console.log(count);
};
this.getCount = function() {
return count;
};
}
const counter = new Counter();
counter.increment(); // 输出 1
console.log(counter.count); // undefined
ES6 Class 实现
class Counter {
#count = 0; // 私有字段(现代浏览器支持)
increment() {
this.#count++;
console.log(this.#count);
}
getCount() {
return this.#count;
}
}
const counter = new Counter();
counter.increment(); // 输出 1
console.log(counter.#count); // 报错
多态
多态允许不同对象对同一方法调用做出不同响应。JavaScript 通过原型继承和接口实现(鸭子类型)支持多态。
原型继承实现
class Animal {
speak() {
throw new Error("必须实现 speak 方法");
}
}
class Dog extends Animal {
speak() {
return "汪汪";
}
}
class Cat extends Animal {
speak() {
return "喵喵";
}
}
function makeSound(animal) {
console.log(animal.speak());
}
makeSound(new Dog()); // 汪汪
makeSound(new Cat()); // 喵喵
鸭子类型实现

function makeSound(obj) {
if (typeof obj.speak === 'function') {
console.log(obj.speak());
}
}
const dog = { speak: () => "汪汪" };
const cat = { speak: () => "喵喵" };
makeSound(dog); // 汪汪
makeSound(cat); // 喵喵
结合封装与多态
class Shape {
#color;
constructor(color) {
this.#color = color;
}
getColor() {
return this.#color;
}
area() {
throw new Error("必须实现 area 方法");
}
}
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(`颜色: ${shape.getColor()}, 面积: ${shape.area()}`);
});






