实现一个once函数,传入函数参数只执行一次
说明:
在js中,包装函数是一个很重要的手法。模板比较通用:
1、包装函数中的一个参数是函数,
2、包装函数最终会返回一个函数,
3、使用闭包来保存一个状态。
/**
* 创建一个只执行一次的函数包装器
* @param {Function} fn - 要包装的函数
* @returns {Function} - 包装后的函数
*/
function once(fn) {
let hasBeenCalled = false;
let result;
return function (...args) {
if (!hasBeenCalled) {
hasBeenCalled = true;
result = fn.apply(this, args);
}
return result;
};
}
// 使用示例
const example = once((x) => {
console.log("函数被调用,参数:", x);
return x * 2;
});
console.log(example(5)); // 输出: 函数被调用,参数: 5, 10
console.log(example(10)); // 输出: 10 (不会再次执行函数)
console.log(example(15)); // 输出: 10 (不会再次执行函数)