一. 推荐使用字面量
<!-- good -->
let obj = {
name: 'Tom',
age: 15,
sex: '男'
}
<!-- bad -->
let obj = {};
obj.name = 'Tom';
obj.age = 15;
obj.sex = '男'
二. 对象设置默认属性的推荐写法
<!-- 推荐 -->
const menuConfig = {
title: "Order",
buttonText: "Send",
cancellabel: true
}
function createMenu (config) {
config = Object.assign(
{
title: "Foo",'
body: "Bar",
buttonText: "Baz",
cancellable: true
},
config
)
}
createMenu(munuConfig)
三. 将对象的属性值保存为局部变量
对象成员嵌套越深,读取速度也就越慢。所以好的经验法则是:如果在函数中需要多次读取一个对象属性,最佳做法是将该属性值保存在局部变量中,避免多次查找带来的性能开销。
<!-- 推荐 -->
let person = {
info: {
sex: '男'
}
}
function getMaleSex () {
let sex = person.info.sex;
if (sex === '男') {
console.log(sex)
}
}
<!-- 不推荐 -->
let person = {
info: {
sex: '男'
}
}
function getMaleSex () {
if (person.info.sex === '男') {
console.log(person.info.sex)
}
}
四. 禁止超过3层的嵌套循环
五. 函数参数越少越好,如果超过两个,要使用ES6的解构语法
<!-- 推荐 -->
function createMenu({title, body, buttonText, cancellable}) {
// ...
}
createMenu({
title: 'Foo',
body: 'Bar',
buttonText: 'Baz',
cancellable: true
})
<!-- 不推荐 -->
function createMenu(title, body, buttonText, cancellable){
// ...
}
六. 使用参数默认值替代使用条件语句进行赋值
<!-- 推荐 -->
function createMicrobrewery(name = "Hipster Brew Co.") {
// ...
}
<!-- 不推荐 -->
function createMicrobrewery(name){
const breweryName = name || "Hipster Brew Co.";
}
七. 最小函数准则
八. 不要写全局方法
<!-- 推荐 -->
class SuperArray extends Array {
diff (comparisonArray) {
const hash = new Set(comparisonArray);
return this.filter(elem => !hash.has(elem));
}
}
<!-- 不推荐 -->
Array.prototype.diff = function diff(comparisonArray) {
const hash = new Set (comparisonArray);
return this.filter(elem => !hash.has(elem));
}
九. 推荐函数式编程
函数式编程可以让代码的逻辑更清晰更优雅。
<!-- 推荐 -->
const programmerOutput = [
{
name: 'Uncle Bobby',
linesOfCode: 500
}, {
name: 'Suzie Q',
linesOfCode: 1500
}, {
name: 'Jimmy Gosling',
linesOfCode: 150
}, {
name: 'Gracle Hopper',
linesOfCode: 1000
}
]
let totalOutput = programmerOutput
.map(output => output.linesOfCode)
.reduce((totalLines, lines) => totalLines + lines, 0 )
十. 定时器在不使用时要进行清除
代码中使用了定时器setTimeout和setInterval,需要在不使用时进行清除。
如果vue2中的this.$nextTick(())可以替代setTimeout就尽量替代