噢,这很聪明! 我正在从David的博客中了解到这一点 。
const isRequired = () => { throw new Error('param is required'); };
const hello = (name = isRequired()) => { console.log(`hello ${name}`) };
// These will throw errors
hello();
hello(undefined);
// These will not
hello(null);
hello('David');
这里的想法是它使用默认参数,例如,如果您不发送任何内容,此处的b
参数将具有默认值:
function multiply(a, b = 1) {
return a * b;
}
因此,在上面,如果不提供name
,它将使用默认值,即抛出错误的函数。
翻译自: https://css-tricks.com/snippets/javascript/required-parameters-for-functions-in-javascript/