js实现once
实现 once 函数的方法
在 JavaScript 中,once 函数通常用于确保某个函数只能被调用一次,后续调用不会再次执行。以下是几种实现方式:
使用闭包和标志位
function once(fn) {
let called = false;
return function(...args) {
if (!called) {
called = true;
return fn.apply(this, args);
}
};
}
使用高阶函数
const once = (fn) => {
let executed = false;
return (...args) => {
if (!executed) {
executed = true;
return fn(...args);
}
};
};
使用 Proxy
function once(fn) {
let called = false;
return new Proxy(fn, {
apply(target, thisArg, args) {
if (!called) {
called = true;
return Reflect.apply(target, thisArg, args);
}
}
});
}
使用 lodash 的 _.once
如果项目中已经使用了 lodash,可以直接使用其提供的 _.once 方法:

const _ = require('lodash');
const initialize = _.once(() => {
console.log('Initialized');
});
注意事项
- 确保
once包装的函数在第一次调用时正确执行,后续调用不会产生副作用。 - 如果需要保留
this绑定,使用apply或call方法确保上下文正确。 - 如果函数需要返回结果,确保只在第一次调用时返回有效值。
这些方法都能有效实现 once 功能,具体选择取决于项目需求和个人偏好。闭包方法是最常见和简单的实现方式。






