js实现复用
代码复用方法
函数封装
将重复逻辑封装成函数,通过参数传递差异化部分。例如计算数组平均值和总和的函数可复用:
function calculateStats(arr, type) {
return type === 'avg'
? arr.reduce((a, b) => a + b, 0) / arr.length
: arr.reduce((a, b) => a + b, 0);
}
模块化开发
使用ES6模块化拆分功能到独立文件:
// utils.js
export const formatDate = (date) => date.toISOString().split('T')[0];
// app.js
import { formatDate } from './utils.js';
console.log(formatDate(new Date()));
高阶函数
通过函数返回函数实现行为定制:
const multiplier = (factor) => (num) => num * factor;
const double = multiplier(2);
console.log(double(5)); // 输出10
类继承与组合
使用class继承或对象组合复用代码:
class Animal {
constructor(name) {
this.name = name;
}
}
class Dog extends Animal {
bark() {
return `${this.name} barks`;
}
}
Mixin模式
通过Object.assign实现多重继承:
const canEat = {
eat() {
console.log(`${this.name} eats`);
}
};
class Cat {
constructor(name) {
this.name = name;
}
}
Object.assign(Cat.prototype, canEat);
自定义Hooks(React)
在React中复用状态逻辑:
function useToggle(initialValue = false) {
const [value, setValue] = useState(initialValue);
const toggle = () => setValue(!value);
return [value, toggle];
}
// 组件中使用
const [isOn, toggleIsOn] = useToggle();
闭包应用
利用闭包保存私有状态:

function createCounter() {
let count = 0;
return {
increment() { count++ },
getCount() { return count }
};
}






