• 函数默认值


            <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>
  • 相关阅读:
    vue 中的单元测试
    redux-学习总结
    React-学习总结
    vuecli 中 chainWebpack 的常用操作
    常用 vue-config.js 配置
    JavaScript 中的 MVC、MVP、MVVM
    日常工作中 @vue/cli 需要关注的一些配置
    Electron 构建超时问题
    JSBridge 原理与封装
    Three.js 之相机
  • 原文地址:https://www.cnblogs.com/wangxi01/p/11590154.html
Copyright © 2020-2023  润新知