模块划分中的修饰符运用
- Public:用于暴露模块中需要被外部使用的接口或功能。例如在一个UI库模块中,可能有一个
Button
组件的创建函数需要被其他模块调用。
// buttonModule.js
// 创建Button的公共函数
export const createButton = (text) => {
const button = document.createElement('button');
button.textContent = text;
return button;
};
- Private:在JavaScript中没有原生的
private
修饰符,但可以通过闭包模拟。模块内部一些辅助函数,不需要被外部访问,可设为“私有”。
// utilsModule.js
const module = (function () {
// 私有函数,用于内部计算
const privateHelper = (a, b) => {
return a + b;
};
// 公共函数,调用私有函数
const publicFunction = (a, b) => {
return privateHelper(a, b);
};
return {
publicFunction
};
})();
// 这里无法直接访问privateHelper,只能访问publicFunction
console.log(module.publicFunction(1, 2));
- Protected:同样在JavaScript原生中没有,在类继承场景下可模拟。在一个基础UI组件模块,一些属性或方法希望子类可访问但外部不可访问。
// baseComponent.js
const BaseComponent = function () {
// 模拟受保护的属性
let _protectedProperty = 'protected value';
// 模拟受保护的方法
const _protectedMethod = () => {
console.log('This is a protected method');
};
this.getProtectedProperty = function () {
return _protectedProperty;
};
this.callProtectedMethod = function () {
_protectedMethod();
};
};
// component.js
const Component = function () {
BaseComponent.call(this);
};
Component.prototype = Object.create(BaseComponent.prototype);
Component.prototype.constructor = Component;
const component = new Component();
// 外部不能直接访问_protectedProperty和_protectedMethod
// 但可以通过继承来访问相关功能
console.log(component.getProtectedProperty());
component.callProtectedMethod();
组件设计中的修饰符运用
- Public:组件的公共属性和方法,供外部使用。例如一个
Modal
组件,它的open
和close
方法应该是公共的。
class Modal {
constructor() {
this.isOpen = false;
}
// 公共方法,打开模态框
open() {
this.isOpen = true;
// 显示模态框的逻辑
}
// 公共方法,关闭模态框
close() {
this.isOpen = false;
// 隐藏模态框的逻辑
}
}
- Private:组件内部的状态管理和一些不希望外部访问的操作。比如
Modal
组件内部的动画处理函数。
class Modal {
constructor() {
this.isOpen = false;
}
// 私有方法,用于处理动画,通过#前缀在ES2022中实现私有
#handleAnimation() {
// 动画逻辑
}
open() {
this.isOpen = true;
this.#handleAnimation();
}
close() {
this.isOpen = false;
this.#handleAnimation();
}
}
- Protected:如果有
Modal
的子类,比如ConfirmModal
,一些方法或属性希望子类能访问但外部不能。
class Modal {
constructor() {
this.isOpen = false;
// 模拟受保护的属性
this._message = 'default message';
}
// 模拟受保护的方法
_updateMessage(newMessage) {
this._message = newMessage;
}
open() {
this.isOpen = true;
}
close() {
this.isOpen = false;
}
}
class ConfirmModal extends Modal {
constructor() {
super();
this._updateMessage('Confirm something?');
}
}