1

I want call function once in java script and for implement this idea I write this code and I use closure

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!" in console. But I notice I can call initialize function many times and create different start function for example

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

This time in output I have twice "view has been set!". How can I fix that. thanks.

Navid
  • 225
  • 2
  • 15

3 Answers3

2

By keeping the structure of calling initialize, you need a closure which works without the first call of initialize.

Then you need a nested function to get the inner function for the working part.

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


const start1 = initialize();
const start2 = initialize();
start1();
start2();
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

When you call initialize function every times a new called variable is created which assigned to value 0.

Orion
  • 248
  • 3
  • 10
0

I believe what you are looking for is a 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() 
Sermet Pekin
  • 357
  • 2
  • 6