JavaScript style for optional callbacks

后端 未结 10 1712
日久生厌
日久生厌 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: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

提交回复
热议问题