JavaScript style for optional callbacks

后端 未结 10 1710
日久生厌
日久生厌 2020-12-02 07:30

I have some functions which occasionally (not always) will receive a callback and run it. Is checking if the callback is defined/function a good style or is there a better w

相关标签:
10条回答
  • 2020-12-02 07:47

    I have sinced moved to coffee-script and found default arguments is a nice way to solve this problem

    doSomething = (arg1, arg2, callback = ()->)->
        callback()
    
    0 讨论(0)
  • 2020-12-02 07:49

    You can also do:

    var noop = function(){}; // do nothing.
    
    function save (callback){
       callback = callback || noop;
       .....do stuff......
    };
    

    It's specially useful if you happen to use the callback in a few places.

    Additionally if you are using jQuery, you already have a function like that, it's called $.noop

    0 讨论(0)
  • 2020-12-02 07:53

    I personally prefer

    typeof callback === 'function' && callback();

    The typeof command is dodgy however and should only be used for "undefined" and "function"

    The problems with the typeof !== undefined is that the user might pass in a value that is defined and not a function

    0 讨论(0)
  • 2020-12-02 07:59

    Simply do

    if (callback) callback();
    

    I prefer to call the callback if supplied, no matter what type it is. Don't let it fail silently, so the implementor knows he passed in an incorrect argument and can fix it.

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