我怎样才能简化检查未定义?
我有这样的代码:
var process = function(next){ //do stuff if(typeof next != 'undefined') { next(a, b, c, d, e); } }
我很厌恶到处打字。 是否有一个全局函数,我可以写,处理检查未定义以及所有的参数?
例如:
_call = function(next){ if(typeof next != 'undefined') next(); };
上面的例子不行,顺便说一下。 因为节点在我这样做的时候抛出一个错误:
_call(next('hello', 'world')); //ERROR! next is undefined
所以也许我可以做到这一点?
_call(next, argument1, argument2, ... )
有一个内置的函数来处理未定义的检查以及所有的参数吗?
不,但你可以自己写一个。
所以也许我可以做到这一点?
_call(next, argument1, argument2, ... )
是:
function _call(fn, ...args) { if (typeof fn == "function") return fn(...args); }
(使用ES6rest和扩展语法,在ES5中它将是fn.apply(null, Array.prototype.slice.call(arguments, 1)
)
这是一个黑客,但你可能能够使用默认参数
(function(next=()=>{}){ //do stuff next(a, b, c, d, e); })();
所以如果不用参数调用,接下来将是一个空的函数,它不会做任何事情
你根本不需要typeof
。 在这种情况下的术语有点奇怪,但这里是解释:
var v; // initialize variable v if (v) {} // works although v has type "undefined" if (notInitialized) {} // ReferenceError: notDefined is not defined
当你有一个参数的function是一样的。 参数始终被初始化,但可能有undefined
的types。
因此,您可以使用
var process = function(next){ //do stuff if (next) { next(a, b, c, d, e); } }
甚至
var process = function(next){ next && next(a, b, c, d, e); }
但是,在实际调用next
之前,可能会检查它是否实际上是一个函数。
如果您使用的是ES6,那么您也可以使用默认参数 ,以防这些参数与您的用例一起使用。
用这个
_call = function(next){ if(next && next != 'undefined' && next != 'null') next(); };
它应该是未定义的,并引发错误。 因为您调用名为next
的函数并将其作为parameter passing给_call
。
这是正确的:
_call(function('hello', 'world'){//do dtuff});
和
_call = function(next){ if(typeof next === 'function') next(); };