用于可选回调的JavaScript样式 [英] JavaScript style for optional callbacks

查看:159
本文介绍了用于可选回调的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 命令是狡猾的,但只能使用undefinedfunction

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆