网站首页 > 博客文章 正文
今天给大家分享几个好的功能封装,在你的项目开发中,一定会用的到,肯定实用。这样写,能提高的编码能力,编写出高效且可维护的JavaScript代码。
功能一,动态加载JS文件
有过一定项目开发经验的同学一定知道,在实际项目开发过程中,会经常碰到需要动态加载一些JS的时候,比如依赖的第三方SDK。那如何封装一个可以动态加载JS的功能函数呢?代码如下
此代码两个核心点:
1. 使用Promise处理异步
2. 使用脚本标签加载和执行JS
// 封装
function loadJS(files, done) {
const head = document.getElementsByTagName('head')[0];
Promise.all(files.map(file => {
return new Promise(resolve => {
const s = document.createElement('script');
s.type = "text/javascript";
s.async = true;
s.src = file;
s.addEventListener('load', (e) => resolve(), false);
head.appendChild(s);
});
})).then(done);
}
// 使用
loadJS(["test1.js", "test2.js"], () => {
});
功能二,递归检索对象属性
当一个对象的属性也是一个对象的时候,如何遍历出这个对象上的所有属性,包括子属性对象上的对象。
使用递归循环遍历
function getAllObjectProperties(obj) {
for (const prop in obj) {
if (typeof obj[prop] === "object") {
getAllObjectProperties(obj[prop]);
} else {
console.log(prop, obj[prop]);
}
}
}
const sampleObject = {
name: "John",
age: 30,
address: {
city: "Example City",
country: "Example Country"
}
};
getAllObjectProperties(sampleObject);
功能三,柯里化(Currying)
将一个采用多个参数的函数转换为一系列函数,每个函数只采用一个参数,这增强了函数使用的灵活性,最大限度地减少了代码冗余,并提高了代码的可读性。
function curryAdd(x) {
return function (y) {
return function (z) {
return x + y + z;
};
};
}
const result = curryAdd(1)(2)(3);
功能四,函数仅执行一次
在某些情况下,特定函数只允许执行一次。这种情况还是挺多的。
once函数包装了另一个函数,确保它只能执行一次
// 封装
function once(fn) {
let executed = false;
return function (...args) {
if (!executed) {
executed = true;
return fn.apply(this, args);
}
};
}
// 执行
const runOnce = once(() => {
});
runOnce();
runOnce();
功能五,添加默认值
如果用户省略参数,则分配一个预定的默认值。
function greetUser(name = "Guest") {
console.log(`Hello, ${name}!`);
}
greetUser(); // 输出: Hello, Guest!
greetUser("John"); // 输出:Hello, John!
功能六,利用Reduce进行数据结构转换
下面这个实例,我需要将数据按指定字段分类出来,只需要将使用reduce封装一个可执行的函数就行。
const employees = [
{ department: "HR", name: "Alice", experience: 3 },
{ department: "IT", name: "Bob", experience: 5 },
{ department: "HR", name: "Charlie", experience: 2 },
{ department: "IT", name: "David", experience: 4 },
{ department: "Finance", name: "Eva", experience: 6 }
];
// 封装
function groupArrayByKey(arr = [], key) {
return arr.reduce((grouped, employee) => {
grouped[employee[key]] = [...(grouped[employee[key]] || []), employee];
return grouped;
}, {});
}
// 使用
groupArrayByKey(employees, "department")
猜你喜欢
- 2024-10-11 JavaScript,ES6,Promise对象,异步编程的一种解决方案,代码
- 2024-10-11 使用 Matter.js 创建物理模拟:牛顿摆
- 2024-10-11 一首歌带你搞懂Promise(歌曲promise)
- 2024-10-11 如何用Vue3和p5.js绘制一个交互式波浪图
- 2024-10-11 IT技术栈:Javascript中Promise的pending、fulfilled和rejected
- 2024-10-11 Node.js中的Promise:回调的替代方案
- 2024-10-11 我终于真正理解 Promise 了!(promise 的理解)
- 2024-10-11 探究JS中Promise函数then的奥秘(js中promise什么意思)
- 2024-10-11 关于js中的promise,与其说是一种语法还不如说是一种思想!
- 2024-10-11 前端-JavaScript异步编程中的Promise
你 发表评论:
欢迎- 07-07Xiaomi Enters SUV Market with YU7 Launch, Targeting Tesla with Bold Pricing and High-Tech Features
- 07-07Black Sesame Maps Expansion Into Robotics With New Edge AI Strategy
- 07-07Wuhan's 'Black Tech' Powers China's Cross-Border Push with Niche Electronics and Scientific Firepower
- 07-07Maven 干货 全篇共:28232 字。预计阅读时间:110 分钟。建议收藏!
- 07-07IT运维必会的30个工具(it运维工具软件)
- 07-07开源项目有你需要的吗?(开源项目什么意思)
- 07-07自动化测试早就跑起来了,为什么测试管理还像在走路?
- 07-07Cursor 最强竞争对手来了,专治复杂大项目,免费一个月
- 最近发表
-
- Xiaomi Enters SUV Market with YU7 Launch, Targeting Tesla with Bold Pricing and High-Tech Features
- Black Sesame Maps Expansion Into Robotics With New Edge AI Strategy
- Wuhan's 'Black Tech' Powers China's Cross-Border Push with Niche Electronics and Scientific Firepower
- Maven 干货 全篇共:28232 字。预计阅读时间:110 分钟。建议收藏!
- IT运维必会的30个工具(it运维工具软件)
- 开源项目有你需要的吗?(开源项目什么意思)
- 自动化测试早就跑起来了,为什么测试管理还像在走路?
- Cursor 最强竞争对手来了,专治复杂大项目,免费一个月
- Cursor 太贵?这套「Cline+OpenRouter+Deepseek+Trae」组合拳更香
- 为什么没人真的用好RAG,坑都在哪里? 谈谈RAG技术架构的演进方向
- 标签列表
-
- ifneq (61)
- 字符串长度在线 (61)
- messagesource (56)
- aspose.pdf破解版 (56)
- promise.race (63)
- 2019cad序列号和密钥激活码 (62)
- window.performance (66)
- qt删除文件夹 (72)
- mysqlcaching_sha2_password (64)
- ubuntu升级gcc (58)
- nacos启动失败 (64)
- ssh-add (70)
- jwt漏洞 (58)
- macos14下载 (58)
- yarnnode (62)
- abstractqueuedsynchronizer (64)
- source~/.bashrc没有那个文件或目录 (65)
- springboot整合activiti工作流 (70)
- jmeter插件下载 (61)
- 抓包分析 (60)
- idea创建mavenweb项目 (65)
- vue回到顶部 (57)
- qcombobox样式表 (68)
- tomcatundertow (58)
- pastemac (61)
本文暂时没有评论,来添加一个吧(●'◡'●)