Skip to content

变量命名规范

函数封装

永远记住一个函数只做一件事情,一个函数不超过 30 行代码,如果超过了需要考虑抽离代码。如果封装的函数只出现一次,考虑封装成内联函数。

函数多参数采用对象

函数的参数大于两个需要考虑使用对象接收,函数参数过多,很容易导致参数的传递错误,这时考虑使用对象将参数进行合并,在函数参数处直接使用对象解构。

⚠️不推荐的:

js
function dealUserInfo(name,age,sex) {}

dealUserInfo('dzp',22,1)

推荐的:

js
function dealUserInfo({name,age,sex}) {}
dealUserInfo({name:'dzp',age:22,sex:1})

函数默认参数代替短路逻辑

⚠️不推荐的:

js
function test(name) {
  name = name || 'dzp'
}

推荐的

js
function test(name='dzp') {}

减少函数副作用

除非功能需要,否则函数的参数不要去修改其值。

多个 if 条件判断使用数组代替

当 if 判断条件>=3 个时,无论在视觉还是维护上都十分难受,因此我们考虑借助数组进行优化设计。

⚠️不推荐的

js
if(name==='dzp' || name==='xiao' || name==='ming') {}

推荐的

js
const names = ['dzp','xiao','ming'] 
if(names.includes(name)) {}

async await 必须捕获错误

错误的信息日志使用 console.error 更加显眼,便于调试发现错误。

bad

csharp
csharp
复制代码  async function test() {
     let Infos = await getInfo()
     let details = await getDetails(Infos.id)
  }

good

javascript
javascript
复制代码  async function test() {
      try{
        let Infos = await getInfo()
        let details = await getDetails(Infos.id)
      }catch(e){
        console.error(e)
      }
   }

对象 or 数组引用

修改或者使用对象、数组时,时刻切记它们为引用,一处修改会造成处处修改。

默认对象采用函数返回

由于 js 中的对象是引用,因此赋默认值的时候最好通过函数,每次都返回一个新对象。

bad:

javascript
javascript
复制代码const defaultCondition = {
  name: '',
  conditionList: [
    {
      conditionCode: '',
      conditionValue: null,
    },
  ],
}
export default {
    data() {
        return {
            condition: {...defaultCondition},
        };
    },
    methods: {
        closeDialog() {
            this.condition =  {...defaultCondition};
            this.configId = null;
            this.$refs.form.resetFields();
        },
    },
};

good:

javascript
javascript
复制代码const getDefaultCondition = () => ({
  name: '',
  conditionList: [
    {
      conditionCode: '',
      conditionValue: null,
    },
  ],
})
export default {
    data() {
        return {
            condition: getDefaultCondition(),
        };
    },
    methods: {
        closeDialog() {
            this.condition = getDefaultCondition();
            this.configId = null;
            this.$refs.form.resetFields();
        },
    },
};