js实现 once 方法

function once(fn) {
    let flag = false;
    let result = null;
    return function (...args) {
        if (flag) {
            return result;
        }
        flag = true;
        result = fn.call(this, ...args);
        return result;
    };
}
let onceFn1 = once((a, b) => {
    return a + b;
});
console.log(onceFn1(1, 2)); // 3
console.log(onceFn1(3, 2)); // 3
console.log(onceFn1(3, 3)); // 3
let onceFn2 = once((a, b) => {
    return a - b;
});
console.log(onceFn2(3, 2)); // 1
console.log(onceFn2(4, 2)); // 1

 

posted @ 2022-08-22 17:41  蓓蕾心晴  阅读(438)  评论(0编辑  收藏  举报