导入
ES5 中的技巧
可选函数参数及其替代方案,ES5简写语法的局限性
在某些情况下,函数参数是可选的。例如,来看下面这段代码:
1function addCalendarEntry(event, date, len, timeout) { 2 date = typeof date === 'undefined' ? new Date().getTime() : date; 3 len = typeof len === 'undefined' ? 60 : len; 4 timeout = typeof timeout === 'undefined' ? 1000 : timeout; 5 6 // ... 7} 8addCalendarEntry('meeting');
addCalendarEntry 函数中有三个参数是可选的。
在 ES5 中,一种常见的可选参数简写方式是使用 ||(逻辑或)运算符。你可以利用逻辑运算的短路特性。
1function addCalendarEntry(event, date, len, timeout) { 2 date = date || new Date().getTime(); 3 len = len || 60; 4 timeout = timeout || 1000; 5 // ... 6} 7addCalendarEntry('meeting');
表达式 value || defaultValue 的结果是 value,当 value 为真值时;如果 || 表达式的第一个操作数为真,则第二个操作数不会被求值。这种现象称为逻辑短路。
当 value 为假值时,value || defaultValue 的结果就是 defaultValue。
虽然这种方法在表面上看起来简洁明了,但有时短路操作不够灵活。所有假值都会被统一处理,包括 0、空字符串 '' 和 false。然而,在某些场景下,我们可能希望将 0 与表示缺失值的 undefined 区分开来处理。