js实现复用
复用实现方法
在JavaScript中实现代码复用可以通过多种方式完成,以下是一些常见且高效的方法:
函数封装
将重复逻辑封装成函数,通过调用函数实现复用。例如计算两数之和:
function add(a, b) {
return a + b;
}
console.log(add(1, 2)); // 3
console.log(add(3, 4)); // 7
高阶函数
接受函数作为参数或返回函数的函数,适用于处理相似流程但不同细节的场景:

function processArray(arr, processor) {
return arr.map(processor);
}
const doubled = processArray([1, 2, 3], x => x * 2);
模块化
使用ES6模块系统将代码拆分到不同文件,通过import/export实现复用:
// math.js
export function square(x) { return x * x; }
// app.js
import { square } from './math.js';
console.log(square(5)); // 25
类继承
通过class和extends实现面向对象编程中的复用:

class Animal {
constructor(name) { this.name = name; }
speak() { console.log(`${this.name} makes noise`); }
}
class Dog extends Animal {
speak() { console.log(`${this.name} barks`); }
}
const d = new Dog('Rex');
d.speak(); // Rex barks
混入模式
通过Object.assign实现多重继承的效果:
const canEat = {
eat() { console.log('Eating'); }
};
const canWalk = {
walk() { console.log('Walking'); }
};
class Person {
constructor(name) { this.name = name; }
}
Object.assign(Person.prototype, canEat, canWalk);
const p = new Person('John');
p.walk(); // Walking
组合函数
将多个函数组合成新函数,实现行为复用:
const compose = (...fns) => x => fns.reduceRight((v, f) => f(v), x);
const add1 = x => x + 1;
const double = x => x * 2;
const addThenDouble = compose(double, add1);
console.log(addThenDouble(5)); // 12
实用工具库
创建包含常用功能的工具对象实现复用:
const utils = {
formatDate(date) { /*...*/ },
validateEmail(email) { /*...*/ }
};
utils.formatDate(new Date());
选择哪种复用方式取决于具体场景和项目规模。函数封装和模块化适合大多数情况,类继承和混入适合复杂对象系统,高阶函数和组合适合函数式编程场景。






