<body> 1. 默认值 <script type="text/javascript"> // bad function test(quantity) { const q = quantity || 1; } // good function test(quantity = 1) { ... } </script> <script type="text/javascript"> doSomething({ foo: 'Hello', bar: 'Hey!', baz: 42 }); // bad function doSomething(config) { const foo = config.foo !== undefined ? config.foo : 'Hi'; const bar = config.bar !== undefined ? config.bar : 'Yo!'; const baz = config.baz !== undefined ? config.baz : 13; } // good function doSomething({ foo = 'Hi', bar = 'Yo!', baz = 13 }) { ... } // better function doSomething({ foo = 'Hi', bar = 'Yo!', baz = 13 } = {}) { //这种是给不传参数的默认值 console.log(foo, bar) } </script> <script type="text/javascript"> // 知识点: defaultProps // bad const Button = ({className}) => { const classname = className || 'default-size'; return <span className={classname}></span> }; // good const Button = ({className = 'default-size'}) => ( <span className={classname}></span> ); // better const Button = ({className}) => <span className={className}></span> } Button.defaultProps = { className: 'default-size' } </script> <script type="text/javascript"> // 知识点: 缺少参数会进入这个方法,项目中我们可以利用这一点做些事情 const required = () => {throw new Error('Missing parameter')}; const add = (a = required(), b = required()) => a + b; add(1, 2) // 3 add(1); // Error: Missing parameter. </script> </body>