可选回调的 JavaScript 样式 [英] JavaScript style for optional callbacks
本文介绍了可选回调的 JavaScript 样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一些函数偶尔(并非总是)会收到回调并运行它.检查回调是否定义/函数是一种很好的风格还是有更好的方法?
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 way?
示例:
function save (callback){
.....do stuff......
if(typeof callback !== 'undefined'){
callback();
};
};
推荐答案
我个人更喜欢
typeof callback === 'function' &&callback();
typeof
命令是狡猾的但是应该只用于 "undefined"
和 "function"
The typeof
command is dodgy however and should only be used for "undefined"
and "function"
typeof !== undefined
的问题在于,用户可能传入已定义的值,而不是函数
The problems with the typeof !== undefined
is that the user might pass in a value that is defined and not a function
这篇关于可选回调的 JavaScript 样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文