简体   繁体   English

在 java 脚本中调用 function 一次并关闭

[英]Call function in java script once with closure

I want call function once in java script and for implement this idea I write this code and I use closure我想在 java 脚本中调用 function 一次,为了实现这个想法,我编写了这段代码并使用了闭包

function initialize() {
  let called = 0;
  return function() {
    if (called > 0) {
      return
    } else {
      called++;
      console.log('view has been set!')
    }

  }
}

const start1 = initialize();
start1();
start1();
start1();

I call start1 function third time and when I run this code I get once this output "view has been set."我第三次调用 start1 function ,当我运行此代码时,我得到一次 output “视图已设置”。 in console.在控制台中。 But I notice I can call initialize function many times and create different start function for example但我注意到我可以多次调用初始化 function 并创建不同的启动 function 例如

const start1 = initialize();
const start2 = initialize();
start1();
start2();

This time in output I have twice "view has been set.".这次在 output 我有两次“视图已设置。”。 How can I fix that.我该如何解决。 thanks.谢谢。

By keeping the structure of calling initialize , you need a closure which works without the first call of initialize .通过保持调用initialize的结构,您需要一个无需第一次调用initialize即可工作的闭包。

Then you need a nested function to get the inner function for the working part.然后你需要一个嵌套的 function 来获得工作部分的内部 function。

 const initialize = (() => { let called = 0; return () => () => { if (called <= 0) { called++; console.log('view has been set;'); } }; })(); const start1 = initialize(); const start2 = initialize(); start1(); start2();

When you call initialize function every times a new called variable is created which assigned to value 0 .当您调用initialize function 时,每次创建一个新的called变量,该变量分配给值0

I believe what you are looking for is a singleton.我相信您正在寻找的是 singleton。 You can try this approach.你可以试试这个方法。

 class initialize { constructor(){ if(. initialize.instance){ this;_data = []. initialize;instance = this. console.log('view has been set;') } return initialize.instance; } dosmt=()=>{ console.log("smt" ) } } const instance = new initialize(); Object;freeze(instance); const start1 = new initialize(); const start2 = new initialize(). const start3 = new initialize(). start1.dosmt() start2.dosmt() start3.dosmt()

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

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