Sunny-117 / js-challenges

✨✨✨ Challenge your JavaScript programming limits step by step

Home Page:https://juejin.cn/column/7244788137410560055

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

实现 执行一次的函数

Sunny-117 opened this issue · comments

实现 执行一次的函数
commented
function myF(fun) {
  let flag = false;
  return function () {
    if (!flag) {
      flag = true;
      return fun.call(this, ...arguments);
    }
  };
}
function sayHi() {
  console.log("hi!");
}
const sayOnce = myF(sayHi);
sayOnce();
sayOnce();

闭包应用

function one(callback){
    let flag = true;
    return function(...args){
        if(!flag) return;
        flag = false;
        return callback(...args);
    }
}
function once(fn) {
  let called = false;

  return function() {
    if (!called) {
      called = true;
      fn.apply(this, arguments);
    }
  }
}

let runOnce = once(function(name) { 
  console.log(`Hello, ${name}!`); 
});

runOnce('Alice'); // 输出:Hello, Alice!
runOnce('Bob');   // 不会有任何输出

function once(fn) {
let flag = false;
return (...args) => {
if (!flag) {
flag = true;
fn.apply(this, args);
}
};
}