1. 解构赋值与变量重命名
解构赋值是一个强大的特性。你知道在赋值的时候可以给变量起别名吗?
const {
prop1: newName1, prop2: newName2 } = object;
这里,我们把 prop1
和 prop2
分别重命名为 newName1
和 newName2
。
2. 使用记忆化提升性能
记忆化是一种缓存函数结果以提升性能的技巧。来看一个简单的实现:
const memoizedFunction = (function () {
const cache = {
};
return function (args) {
if (!(args in cache)) {
cache[args] = computeResult(args);
}
return cache[args];
};
})();
通过缓存结果,我们避免了重复的计算。
3. 函数柯里化用于组合函数
柯里化允许创建可复用和可组合的函数。看看这个简洁的柯里化函数:
const curry = (fn, ...args) =>
args.length >= fn.length ? fn(...args) : (...moreArgs)