School-of-Website-Engineering/future-front-end

前端 JS 规范

Opened this issue · 0 comments

前端 JS 规范

变量

命名方式:小驼峰

命名规范:前缀名词

// bad
let setCount = 10;

// good
let maxCount = 10;

常量

命名方式:全部大写

命名规范:多个单词时使用分隔符**_**

// bad
const serverErrorCode = {
	success: 200,
	repeat: 444,
};

// good
const SERVER_ERROR_CODE = {
	SUCCESS: 200,
	REPEAT: 444,
};

函数

命名方式:小驼峰

命名规范:前缀动词

// bad
function wordClass() {}

// good
function saveWordClass() {}

常用动词:can、has、is、load、get、set

命名方式:大驼峰

命名规范:前缀名词

// bad
class person {}

// good
class Person {}

注释

单行

// 单行注释,注意前面的空格
let maxCount = 123;

多行

/**
 * 多行注释
 * /

减少嵌套

确定条件不允许时,尽早返回。经典使用场景:校验数据

// bad
if (condition1) {
    if (condition2) {
        ...
    }
}

// good
if (!condition1) return
if (!condition2) return
...

减少特定标记值

使用常量进行自解释

// bad
type: 1; // 1代表新增  2代表修改

// good
const MODIFY_TYPE = {
	ADD: 1,
	EDIT: 2,
};

type: MODIFY_TYPE.ADD;

表达式

尽可能简洁表达式

// bad
if (name === "") {
}
if (collection.length > 0) {
}
if (notTrue === false) {
}

// good
if (!name) {
}
if (collection.length) {
}
if (notTrue) {
}

分支较多处理

对于相同变量或表达式的多值条件,用 switch 代替 if。

// bad
let type = typeof variable;
if (type === "object") {
	// ......
} else if (type === "number" || type === "boolean" || type === "string") {
	// ......
}

// good
switch (typeof variable) {
	case "object":
		// ......
		break;
	case "number":
	case "boolean":
	case "string":
		// ......
		break;
}

使用变量名自解释 V1.1

逻辑复杂时,建议使用变量名自解释,而不是晦涩难懂的简写。

// bad
function(value) {
    return !helpers.req(value) || this.entity.entVocabularyEntries.filter(item => item.vocabularyEntryName === value).length < 2
}

// good
function(value) {
    let entVocabularyList = this.entity.entVocabularyEntries
    let repeatCount = entVocabularyList.filter(item => item.vocabularyEntryName === value).length
    return !helpers.req(value) || repeatCount < 2
}

使用函数名自解释 V1.1

遵循单一职责的基础上,可以把逻辑隐藏在函数中,同时使用准确的函数名自解释。

// bad
if (modifyType === MODIFY_TYPE.ADD) {
    batchVariableAPI(data).then(() => {
        this.closeModal()
        this.$toast.show('添加变量成功')
    })
} else {
  updateVariableAPI(data).then(() => {
        this.closeModal()
        this.$toast.show('修改变量成功')
    })
}

// good
modifyType === MODIFY_TYPE.ADD  this._insertVariable(data) : this._updateVariable(data)

_insertVariable() {
    batchVariableAPI(data).then(() => this._successOperation('添加变量成功'))
}

_updateVariable() {
    updateVariableAPI(data).then(() => this._successOperation('修改变量成功'))
}

_successOperation(toastMsg) {
    this.closeModal()
    this.$toast.show(toastMsg)
}