JavaScript - self-executing anonymous functions and callback

后端 未结 2 1859
长情又很酷
长情又很酷 2020-12-28 21:06

Can I use callback with self-executing function?
If yes, have you seen any examples?

JavaScript self-executing function:

(fun         


        
相关标签:
2条回答
  • 2020-12-28 21:38

    Something like that?

    (function(callback){
    
      //Do Stuff
    
      //Callback
      if(typeof callback === 'function') {
          callback();
      }
    })(myCallback);
    
    0 讨论(0)
  • 2020-12-28 21:45

    Of course you can - this is common way of enclosing your variables within some function so they do not interfere with global variables (or from separate closures).

    Some example:

    (function(){
    
        var counter = 0;
        var step = function(){
            counter++;
            console.log(counter + ' Mississipi...');
        };
    
        setInterval(step, 1000);
    
    })();
    
    (function(){
    
        var counter = 0;
        var step = function(){
            counter++;
            console.log('3 seconds passed for a ' + counter + ' time');
        };
    
        setInterval(step, 3000);
    
    })();
    

    Thanks to the closures, the variables from them are not interfering with the ones from different closure (different anonymous function).

    Working example in this jsfiddle.

    EDIT:

    Is you want to execute the code from some callback in such function, you may write something like that:

    var my_own_callback = function(data){
        // some code for callback working on data passed
    };
    // ...
    (function(callback){
        var result; // future data sent to callback
        // do whatever you need here
        callback(result);
    })(my_own_callback);
    

    or even like that:

    (function(callback){
        var result; // data that will be sent to callback
        // do whatever you need here
        callback(result);
    })(function(data){
        // code for callback using data set to this callback
    });
    

    which, however, seems to be rather careless and unnecessarily increasing the complexity of your code.

    0 讨论(0)
提交回复
热议问题