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; // 私有字段(ES2022)
increment() {
this.#count++;
console.log(this.#count);
}
getCount() {
return this.#count;
}
}
多态
多态允许不同对象对同一方法表现出不同行为,通常通过继承和接口实现(JavaScript 无接口,但可通过 duck typing 模拟)。

继承实现多态
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 Dog(), new Cat()];
animals.forEach(animal => animal.makeSound());
// 输出: Bark! / Meow!
Duck Typing 模拟多态
function playSound(entity) {
if (typeof entity.makeSound === 'function') {
entity.makeSound();
}
}
const dog = { makeSound: () => console.log("Bark!") };
const robot = { beep: () => console.log("Beep!") };
playSound(dog); // 输出: Bark!
playSound(robot); // 无输出(不符合"鸭子类型")
关键注意事项
- 封装:优先使用 ES6 的私有字段(
#)或闭包保护数据,避免直接暴露属性。 - 多态:通过方法重写或 duck typing 实现,注意检查对象是否实现所需方法。
- 性能:闭包实现的私有变量会为每个实例创建方法副本,而 ES6 私有字段是共享的。






