网站首页 > 博客文章 正文
今天给大家分享几个好的功能封装,在你的项目开发中,一定会用的到,肯定实用。这样写,能提高的编码能力,编写出高效且可维护的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
你 发表评论:
欢迎- 最近发表
-
- 给3D Slicer添加Python第三方插件库
- Python自动化——pytest常用插件详解
- Pycharm下安装MicroPython Tools插件(ESP32开发板)
- IntelliJ IDEA 2025.1.3 发布(idea 2020)
- IDEA+Continue插件+DeepSeek:开发者效率飙升的「三体组合」!
- Cursor:提升Python开发效率的必备IDE及插件安装指南
- 日本旅行时想借厕所、买香烟怎么办?便利商店里能解决大问题!
- 11天!日本史上最长黄金周来了!旅游万金句总结!
- 北川景子&DAIGO缘定1.11 召开记者会宣布结婚
- PIKO‘PPAP’ 洗脑歌登上美国告示牌
- 标签列表
-
- ifneq (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)
- vue数组concat (56)
- tomcatundertow (58)
- pastemac (61)
本文暂时没有评论,来添加一个吧(●'◡'●)