JavaScript样式:可选回调 [英] JavaScript Style : optional callbacks
本文介绍了JavaScript样式:可选回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一些函数,我想要偶尔运行回调但不总是,是检查回调是否定义/函数是一个好的风格还是有更好的方法?
I have some functions which I will want to ocasionally run a callback in but not always, 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回调==='function'&& callback();
typeof
命令很简单, undefined
和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屋!
查看全文