js实现封装
封装的概念
封装是面向对象编程的核心概念之一,指将数据(属性)和操作数据的方法(行为)捆绑在一起,并隐藏内部实现细节,仅暴露必要的接口。在JavaScript中,封装可以通过多种方式实现。
使用构造函数和原型
通过构造函数定义对象的属性和方法,利用原型链共享方法,避免每次实例化都重新创建方法。

function Person(name, age) {
// 私有变量(通过闭包实现)
let _id = Math.random();
// 公开属性
this.name = name;
this.age = age;
// 特权方法(可访问私有变量)
this.getId = function() {
return _id;
};
}
// 共享方法
Person.prototype.greet = function() {
return `Hello, I'm ${this.name}`;
};
使用ES6 Class语法
ES6的class语法糖提供了更清晰的封装方式,结合#前缀可定义私有字段(ES2022+)。

class Person {
// 私有字段
#id;
constructor(name, age) {
this.#id = Math.random();
this.name = name;
this.age = age;
}
// 公共方法
greet() {
return `Hello, my ID is ${this.#getId()}`;
}
// 私有方法
#getId() {
return this.#id;
}
}
使用闭包实现私有性
通过IIFE(立即执行函数)创建闭包环境,隐藏私有成员。
const counter = (function() {
let _count = 0;
return {
increment() {
_count++;
},
getCount() {
return _count;
}
};
})();
使用模块模式
利用ES6模块的export和import实现文件级封装,每个模块有自己的作用域。
// person.js
let _idCounter = 0;
export class Person {
constructor(name) {
this.id = ++_idCounter;
this.name = name;
}
}
注意事项
- 现代JavaScript推荐使用
class语法结合#私有字段 - 旧版环境可通过闭包模拟私有性
- 模块化封装适合大型项目组织代码
- 避免过度封装导致代码复杂度增加






