原生JS封装组件:构造函数模式与ES6 Class对比
以原生JS弹窗组件Modal为统一示例,从实例状态、原型复用、私有成员、组件继承与事件销毁五个维度对比构造函数模式与ES6 Class的差异与选型依据。
在不使用框架的情况下用原生 JavaScript 封装 UI 组件,构造函数模式和 ES6 class 都可以完成完全一致的交互功能,底层也都依赖函数对象、prototype 原型链和 new 实例化机制。两者的核心差别体现在实例约束、原型方法属性特征、私有状态隔离能力以及派生子组件的维护成本上:现代浏览器项目或已接入构建工具的工程优先选用 ES6 class;需要在无转译环境下直接兼容旧版浏览器、或刻意通过函数闭包彻底隐藏内部状态时,构造函数模式依然适用。下面以一个可复用的原生 Modal 弹窗组件为统一案例,逐步对比两种模式的具体写法与取舍依据。
一、封装一个原生组件要解决哪些实际问题
评判两种模式谁更合适,不能只看代码行数,而要看它们如何解决组件在页面中长期运行时的四个真实需求。为了保证对比客观,后文两种实现都会围绕同一套 Modal 弹窗需求展开:
- 配置合并与实例独立:页面上可能同时存在提示弹窗和表单弹窗,每个实例必须独立持有自己的标题、内容、DOM 节点和显示状态,不能互相覆盖。
- 方法共享与内存控制:
open、close、destroy等操作逻辑相同,应当放在原型上让所有实例共享,避免每创建一个组件就在内存中重复生成一份函数。 - 事件绑定与销毁清理:弹窗需要监听关闭按钮、遮罩层和键盘
Escape键。关闭或卸载组件时若忘记解绑document上的事件,会留下无法回收的引用。 - 内部保护与二次扩展:不希望外部代码随意篡改弹窗当前的内部开关标记;当业务需要派生出带“确认 / 取消”回调的
ConfirmModal时,子组件要能稳定复用父类逻辑。
二、构造函数模式:按步骤实现 Modal 组件
在 ES6 普及之前,原生 JS 组件普遍采用“构造函数 + 原型方法”的组合。它的思路很直接:用函数本身初始化每个实例独有的数据,再把所有实例共用的人机交互方法挂到函数的 prototype 属性上。
实现步骤与完整代码示例
在标准的 HTML 页面中引入一段 <script>,按下面四步即可完成构造函数版的 Modal 组件。注意代码中为了向后兼容 ES5 环境,未使用 class 或解构赋值语法:
- 构建函数体并检查
new调用:通过if (!(this instanceof Modal))拦截忘记写new的直接调用,自动纠正为实例化返回,避免this意外指向window或在严格模式下报错。 - 保存实例状态并缓存事件函数:把当前弹窗的 DOM 元素
this._el、打开状态this._isOpen保存在实例自身,同时用.bind(this)生成固定引用的处理函数并保存下来,方便后续销毁时精准解绑。 - 在原型上定义交互方法:分别定义
_render、_bindEvents、open、close和destroy。为了防止外部传入的标题文本带入恶意脚本,渲染标题和正文时使用textContent而不是直接拼接 HTML 字符串。
// modal-constructor.js(可在普通浏览器 <script> 中直接运行)
function Modal(options) {
if (!(this instanceof Modal)) {
return new Modal(options);
}
var opts = options || {};
this.title = opts.title || '提示';
this.content = opts.content || '';
this.closeOnBackdrop = opts.closeOnBackdrop !== false;
this._isOpen = false;
this._el = null;
// 缓存绑定后的事件函数引用,确保 destroy 时能够移除
this._boundBackdropClick = this._handleBackdropClick.bind(this);
this._boundKeydown = this._handleKeydown.bind(this);
this._render();
this._bindEvents();
}
Modal.prototype._render = function () {
var overlay = document.createElement('div');
overlay.className = 'my-modal-overlay';
overlay.style.cssText = 'position:fixed;inset:0;display:none;align-items:center;justify-content:center;background:rgba(0,0,0,0.45);z-index:999;';
var box = document.createElement('div');
box.className = 'my-modal-box';
box.style.cssText = 'width:360px;max-width:90%;background:#fff;border-radius:8px;padding:20px;box-sizing:border-box;';
var header = document.createElement('div');
header.style.cssText = 'display:flex;justify-content:space-between;align-items:center;margin-bottom:12px;';
var titleEl = document.createElement('strong');
titleEl.textContent = this.title;
var closeBtn = document.createElement('button');
closeBtn.type = 'button';
closeBtn.textContent = '×';
closeBtn.setAttribute('data-action', 'close');
var body = document.createElement('div');
body.className = 'my-modal-body';
body.textContent = this.content;
header.appendChild(titleEl);
header.appendChild(closeBtn);
box.appendChild(header);
box.appendChild(body);
overlay.appendChild(box);
document.body.appendChild(overlay);
this._el = overlay;
this._box = box;
};
Modal.prototype._bindEvents = function () {
this._el.addEventListener('click', this._boundBackdropClick);
document.addEventListener('keydown', this._boundKeydown);
};
Modal.prototype._handleBackdropClick = function (event) {
var isCloseBtn = event.target.getAttribute('data-action') === 'close';
var isBackdrop = this.closeOnBackdrop && event.target === this._el;
if (isCloseBtn || isBackdrop) {
this.close();
}
};
Modal.prototype._handleKeydown = function (event) {
if (this._isOpen && event.key === 'Escape') {
this.close();
}
};
Modal.prototype.open = function () {
if (!this._el || this._isOpen) return;
this._el.style.display = 'flex';
this._isOpen = true;
};
Modal.prototype.close = function () {
if (!this._el || !this._isOpen) return;
this._el.style.display = 'none';
this._isOpen = false;
};
Modal.prototype.destroy = function () {
if (!this._el) return;
this._el.removeEventListener('click', this._boundBackdropClick);
document.removeEventListener('keydown', this._boundKeydown);
if (this._el.parentNode) {
this._el.parentNode.removeChild(this._el);
}
this._el = null;
this._box = null;
this._isOpen = false;
};
在页面中通过点击按钮触发实例化并打开弹窗,调用方式如下:
var tipModal = new Modal({
title: '操作提示',
content: '草稿内容已保存到本地。'
});
tipModal.open();
Modal.prototype 上的方法默认是可枚举的(enumerable: true)。如果有代码用 for (var k in tipModal) 遍历实例属性且忘记判断 hasOwnProperty,就会把 open、close 等方法名一并遍历出来。此外,以下划线开头的 _isOpen 仅仅是团队命名约定,外部依然可以直接读写 tipModal._isOpen。
三、ES6 Class 模式:同等功能的现代写法
ES6 引入了 class 关键字后,上面分散在函数体和 prototype 上的代码被收拢到同一个大括号代码块内。从运行原理上看,class 并没有在 JavaScript 中创造出一套脱离原型的经典面向对象系统——用 typeof Modal 检测依然返回 "function",实例的原型也依然指向 Modal.prototype。但它把很多容易写漏的工程约束变成了语法内置行为。
下面是用 ES6 class 实现的完整 Modal 组件。代码使用了 ES2022 规范支持的 # 私有字段(现代主流浏览器 Chrome 74+、Firefox 90+、Safari 14.1+、Edge 79+ 及 Node.js 12+ 均已原生支持;若目标用户包含更老版本的浏览器,需要配合 Babel 或 TypeScript 转译后再发布):
// modal-class.js(现代浏览器原生 ESM 或打包环境)
class Modal {
// 私有状态与私有 DOM 引用,外部无法直接读取或篡改
#isOpen = false;
#el = null;
#boundBackdropClick;
#boundKeydown;
constructor(options = {}) {
const {
title = '提示',
content = '',
closeOnBackdrop = true
} = options;
this.title = title;
this.content = content;
this.closeOnBackdrop = closeOnBackdrop;
this.#boundBackdropClick = this.#handleBackdropClick.bind(this);
this.#boundKeydown = this.#handleKeydown.bind(this);
this.#render();
this.#bindEvents();
}
#render() {
const overlay = document.createElement('div');
overlay.className = 'my-modal-overlay';
overlay.style.cssText = 'position:fixed;inset:0;display:none;align-items:center;justify-content:center;background:rgba(0,0,0,0.45);z-index:999;';
const box = document.createElement('div');
box.className = 'my-modal-box';
box.style.cssText = 'width:360px;max-width:90%;background:#fff;border-radius:8px;padding:20px;box-sizing:border-box;';
const header = document.createElement('div');
header.style.cssText = 'display:flex;justify-content:space-between;align-items:center;margin-bottom:12px;';
const titleEl = document.createElement('strong');
titleEl.textContent = this.title;
const closeBtn = document.createElement('button');
closeBtn.type = 'button';
closeBtn.textContent = '×';
closeBtn.dataset.action = 'close';
const body = document.createElement('div');
body.className = 'my-modal-body';
body.textContent = this.content;
header.append(titleEl, closeBtn);
box.append(header, body);
overlay.appendChild(box);
document.body.appendChild(overlay);
this.#el = overlay;
this._box = box; // 保留给子组件插入按钮等扩展使用
}
#bindEvents() {
this.#el.addEventListener('click', this.#boundBackdropClick);
document.addEventListener('keydown', this.#boundKeydown);
}
#handleBackdropClick(event) {
const isCloseBtn = event.target.dataset.action === 'close';
const isBackdrop = this.closeOnBackdrop && event.target === this.#el;
if (isCloseBtn || isBackdrop) {
this.close();
}
}
#handleKeydown(event) {
if (this.#isOpen && event.key === 'Escape') {
this.close();
}
}
get isOpen() {
return this.#isOpen;
}
open() {
if (!this.#el || this.#isOpen) return;
this.#el.style.display = 'flex';
this.#isOpen = true;
}
close() {
if (!this.#el || !this.#isOpen) return;
this.#el.style.display = 'none';
this.#isOpen = false;
}
destroy() {
if (!this.#el) return;
this.#el.removeEventListener('click', this.#boundBackdropClick);
document.removeEventListener('keydown', this.#boundKeydown);
this.#el.remove();
this.#el = null;
this._box = null;
this.#isOpen = false;
}
}
与构造函数版本相比,这里只对外暴露了一个只读访问器 get isOpen(),而真正控制弹窗状态和 DOM 节点的 #isOpen、#el 都在语言层被完全隔离。如果外部尝试执行 modal.#isOpen = true,代码在解析阶段就会直接报错。
四、五个关键维度的正面对比
把两段代码放在一起,不能只用“更现代”或“更传统”来概括差异。在实际编写和维护组件时,以下五个维度直接决定了代码出错的概率和可扩展性。
| 对比维度 | 构造函数模式 | ES6 Class 模式 |
|---|---|---|
| 调用安全与声明提升 | 函数声明会提升,声明前即可调用;忘记写 new 时默认仍可执行,必须手写 instanceof 或 new.target 防护。 |
存在暂时性死区(TDZ),声明前引用报错;内部自动开启严格模式,不加 new 调用直接抛出 TypeError。 |
| 原型方法可枚举性 | 通过 Modal.prototype.open = ... 挂载的方法默认 enumerable: true,可被 for...in 遍历到。 |
类体中定义的方法默认 enumerable: false,与原生内置对象的方法行为保持一致,遍历属性时更干净。 |
| 私有状态隔离方式 | 只能靠下划线约定(伪私有)、在构造函数内用闭包(会牺牲原型内存复用),或额外维护一个外部 WeakMap 映射实例。 |
原生支持 #field 与 #method,私有字段绑定在实例内部槽中,外部与子类都无法直接越权修改。 |
| 组件继承与扩展成本 | 需要组合 Parent.call(this)、Object.create(Parent.prototype) 和修复 constructor,静态方法还需手动设置原型。 |
通过 extends 与 super() 一步到位,同时建立实例原型链与静态方法原型链。 |
| 运行环境依赖 | ES5 语法即可在 IE9–IE11 及所有旧版浏览器中无需编译直接运行。 | 基础 class 需 ES6+ 环境;使用 # 私有字段需较新浏览器或通过 Babel/TypeScript 编译降级。 |
1. 私有状态封装:闭包 / WeakMap 对照 # 私有字段
在构造函数模式中,如果确实想让 _isOpen 对外部完全不可见,通常有两种做法:一种是把 open 和 close 直接写进构造函数内部通过闭包访问局部变量 var isOpen = false,但这会让每个弹窗实例都重新生成一套方法函数;另一种是在模块作用域定义一个 var stateMap = new WeakMap(),由原型方法通过 stateMap.get(this) 读取状态,这虽然保留了原型复用,但写法繁琐。
ES6 class 的 #isOpen 兼顾了两者:方法依然挂在 Modal.prototype 上共享一份内存,同时只有类体内部的代码能够访问 this.#isOpen。
2. 派生子组件:ConfirmModal 的继承实现差异
组件库开发中最常见的问题是如何基于基础弹窗扩展出带确定和取消按钮的 ConfirmModal。在这件事上,两种模式的代码量和出错风险拉开了最明显的差距。
以派生 ConfirmModal 为例,两段实现代码的对比非常直观。构造函数模式需要手动串联原型链和修补 constructor:
// 构造函数版子组件:手动借用构造函数并重设原型
function ConfirmModal(options) {
Modal.call(this, options);
this.onConfirm = options && options.onConfirm;
this._appendFooter();
}
ConfirmModal.prototype = Object.create(Modal.prototype);
ConfirmModal.prototype.constructor = ConfirmModal;
ConfirmModal.prototype._appendFooter = function () {
var self = this;
var footer = document.createElement('div');
footer.style.cssText = 'margin-top:16px;text-align:right;';
var okBtn = document.createElement('button');
okBtn.type = 'button';
okBtn.textContent = '确认';
okBtn.addEventListener('click', function () {
if (typeof self.onConfirm === 'function') {
self.onConfirm();
}
self.close();
});
footer.appendChild(okBtn);
this._box.appendChild(footer);
};
而同样的逻辑写成 ES6 class,不仅不用手动操作 Object.create,在需要扩展父类的 destroy 时也能直接通过 super.destroy() 调用,省去了 Modal.prototype.destroy.call(this) 的冗长写法:
// ES6 Class 版子组件:通过 extends 与 super 完成扩展
class ConfirmModal extends Modal {
constructor(options = {}) {
super(options);
this.onConfirm = options.onConfirm;
this.#appendFooter();
}
#appendFooter() {
const footer = document.createElement('div');
footer.style.cssText = 'margin-top:16px;text-align:right;';
const okBtn = document.createElement('button');
okBtn.type = 'button';
okBtn.textContent = '确认';
okBtn.addEventListener('click', () => {
if (typeof this.onConfirm === 'function') {
this.onConfirm();
}
this.close();
});
footer.appendChild(okBtn);
this._box.appendChild(footer);
}
}
两者的行为在运行时还有一个重要区别:在 ES6 子类的 constructor 中,如果在调用 super(options) 之前就去读取或赋值 this.onConfirm,会立刻抛出 ReferenceError。这是因为 ES6 规定必须由父类先构造基础实例(包括父类的 # 私有槽位),再交给子类做增量初始化;而构造函数模式则先生成子类的空 this 对象,再交给父类填充属性。
五、实际开发中的选型依据与常见误区
决定采用哪一种封装模式,应当依据项目真实的运行环境和组件复杂度来判断,而不是盲目追求新语法。
明确的选型依据
- 优先使用 ES6 Class 的场景:开发现代 Web 应用、内部后台系统或 NPM 组件包(配有 Vite/Webpack/Rollup 等构建工具);组件存在基类与子类的层级扩展关系;需要用
#私有字段严格限制外部误操作;多人协作需要清晰的语法边界。 - 保留构造函数模式的场景:向老旧系统嵌入一段原生脚本、页面不允许引入编译流程且必须支持 IE11;或者组件极其简单,且有意通过纯函数闭包隔离全部状态而不对外暴露任何原型结构。
封装过程中最容易踩的三个坑
destroy无法真正移除全局事件:如果绑定时写成document.addEventListener('keydown', this._handleKeydown.bind(this)),销毁时再写一遍removeEventListener('keydown', this._handleKeydown.bind(this))是无效的,因为两次.bind(this)返回的是两个不同的函数对象。无论用构造函数还是class,都必须在初始化阶段把绑定后的引用保存到实例上,销毁时传入同一个引用。- 在 Class 中把所有方法都写成箭头函数:部分开发者为了省去
this指向排查,会把open = () => {}、close = () => {}全部写成类字段箭头函数。这样做不仅让每个实例都各自持有一份函数副本、失去了原型共享的内存优势,还会导致子类无法通过super.open()调用父类方法。 - 通过修改原型对象破坏了
constructor指向:在构造函数模式中,如果为了省事写成Modal.prototype = { open: ..., close: ... },会把原本指向Modal的constructor覆盖掉。之后如果外部代码或工具库依赖instance.constructor判断组件类型,得到的结果会变成Object。
Modal() // 构造函数版受 instanceof 保护返回实例;Class 版直接抛出 TypeError
Object.keys(Modal.prototype) // 构造函数版包含 ["_render", ... "open", "close"];Class 版返回 []
confirmModal instanceof Modal // 两种继承写法均返回 true
理解了实例属性、原型共享、私有隔离与事件销毁这四条主线,无论是维护早期的构造函数组件库,还是基于 ES6 class 编写新的原生组件,都能按实际运行条件做出稳妥的技术选择。
JS对象数组怎么根据指定属性去重
2026-11-22 21:13:52
Chrome与Firefox在JS事件循环实现上有哪些差异?
2026-11-22 19:39:09
JavaScript怎么统计包含Symbol和不可枚举属性的对象大小
2026-11-22 18:50:44
用JavaScript编写支持括号优先级的科学计算器逻辑
2026-11-22 16:41:45
JavaScript对象取值:点号与方括号表示法的区别及用法
2026-11-22 16:18:10








![为什么JS对象直接转字符串显示[object Object]](https://img.javascript.cn/tit/articles/13236/20261106/84aa86eb15b66540a3d64b4a7a62b181d4058395daf4aec8f716e9fa4f562f53.webp)