今天给大家分享几个好的功能封装,在你的项目开发中,一定会用的到,肯定实用。这样写,能提高的编码能力,编写出高效且可维护的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")