adding callback to function - always

后端 未结 3 2209
忘了有多久
忘了有多久 2021-02-09 06:53

I found myself using a weird way to add callback functions to my functions and I was wondering if there is a more generic way to add callbacks to functions, best case I would ha

相关标签:
3条回答
  • 2021-02-09 07:26

    You could, if you really want to, extend Function.prototype with a .cb prototype. Something like:

    Function.prototype.cb = function(cb){
       var self = this;
       return function(){
          self.callback = cb || function(){};
          self.apply(self, arguments);
       }
    }
    

    then your code would compress to:

    var myFunc = function(obj){
       // some code
    
       this.callback(); // callback will always be defined
    }
    

    and the call would slightly change:

    myFunc.cb(function(){
       // callback code
    })(myObj);
    

    Just an idea. You can make the syntax pretty much whatever you want.

    0 讨论(0)
  • 2021-02-09 07:36

    Not sure what you are trying to do here, but a way to add a callback that seems more straight forward:

    function( obj, callback ) {
       if(callback) {
          callback();
       }
    }
    
    0 讨论(0)
  • 2021-02-09 07:43

    I prefer a formal parameter:

    var myFunc = function(obj, callback) {
       ...
    }
    

    This way it makes it obvious that there is a callback. You also don't have to mess around with the arguments object; you can just check to see if callback is undefined, and then check to see if it is of the appropriate type (Function).

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