繁体   English   中英

防止多次调用相同的 javascript function

[英]Prevent same javascript function being called multiple times

我有一个 javascript function initStandardProviders (),当我加载应用程序时正在呈现它,并且相同的 function 也是从不同的模块加载的。 有没有一个选项可以防止这个 function 在同一个 function 中多次加载?

function initStandardProviders(){
//A random function which should be loaded only once.
}

我们可以将闭包用于这些目的

 var makeFunctionCalledOnce = function(fn){
    let called = false;
    return function(...args){
        if(!called){
            called = true;
            fn.call(this,...args);
        }
    }
  }

现在您可以将任何function 转换为“曾经调用过的函数”

function initStandardProviders(){
//A random function which should be loaded only once.
}

let newInitStandardProviders = makeFunctionCalledOnce(initStandardProviders);

// now just call newInitStandardProviders on runtime instead of initStandardProviders

您可以在 IIFE 中设置一个标志,并在运行时将其打开。 如果标志已经打开,不要做任何事情:

const initStandardProviders = (() => {
  let haveRun = false;
  return () => {
    if (haveRun) {
      return;
    }
    haveRun = true;
    //A random function which should be loaded only once.
  };
})();

 const initStandardProviders = (() => { let haveRun = false; return () => { if (haveRun) { return; } haveRun = true; //A random function which should be loaded only once. console.log('running main function body'); }; })(); initStandardProviders(); initStandardProviders(); initStandardProviders();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM